gpt4 book ai didi

java - 如何从对象列表中返回 HashMap?

转载 作者:行者123 更新时间:2023-12-02 03:15:47 24 4
gpt4 key购买 nike

目前,我正在尝试返回一个HashMap。使用具有 50 个或更多条目的 ArrayList 参数。

public static HashMap<String, Doctor> getDoctorHash(ArrayList<Doctor> doctorList) {

HashMap<String, Doctor> hm = new HashMap<>();

for(Doctor doctor : doctorList) {
hm.put(doctor.getId(), doctor);
}

return hm;
}

我将 Id 作为键传递,将 doctor 对象作为值传递..

我的Doctor类(class)很简单:

public class Doctor {
private String firstName, lastName, id;

public Doctor(String firstName, String lastName, String id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
//getter and setters etc.
}

最佳答案

不确定为什么要这样做(您可以使用 Java8 流并过滤列表中的名字),但您已经很接近了。

public static HashMap<String, Doctor> getDoctorHash(ArrayList<Doctor> doctorList) {

HashMap<String, Doctor> hm = new HashMap<>();

for(int i = 0; i < doctorList.size(); i++) {
hm.put(doctorList.get(i).getFirstName(), doctorList.get(i));
}

return hm;
}

或者,更简单

public static HashMap<String, Doctor> getDoctorHash(ArrayList<Doctor> doctorList) {

HashMap<String, Doctor> hm = new HashMap<>();

for(Doctor d : doctorList) {
hm.put(d.getFirstName(), d);
}

return hm;
}

然后,您必须 Doctor d = doctorMap.get("firstname") 获取一些 firstname

关于java - 如何从对象列表中返回 HashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com