[英]Searching through an ArrayList to find an object with a certain field value
我有數組列表ArrayList doctors,該列表存儲存儲一些醫生詳細信息的對象。 每個醫生都有一個唯一的ID字段。 有沒有一種方法可以在陣列列表中搜索具有特定ID值的醫生?
您可以像這樣在ArrayList上使用流:
Optional<Doctor> getUniqueDoctorById(List<Doctor> list, String id) {
return list.stream()
.filter(doctor -> doctor.getId().equals(id))
.findFirst();
}
在這里,您會看到流式傳輸列表並過濾所有醫生ID等於您要搜索的ID的醫生。
嘗試這樣的事情。
private static Doctor queryDoctorById(List<Doctor> doctors, int id) {
Doctor doctor = null;
for (Doctor doc : doctors) {
if (doc.id == id) {
doctor = doc;
break;
}
}
return doctor;
}
// is a sample object representing doctor
protected static class Doctor {
public String name;
public int id;
}
最簡單但可能不是最有效的解決方案,我假設您為所有字段設置了帶有設置器/獲取器的“醫生”,否則您將使用d.id而不是d.getId(),但這不是一個好習慣:
我還假設ID可能包含字母和數字,並以字符串表示。 如果是數字,則應使用==代替.equals
public Doctor findDoctorById(desiredID) {
for(Doctor d : doctors) {
if (d.getId().equals(desiredID) {
return d;
}
}
System.out.println("No doctors with that ID!");
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.