【问题标题】:Searching through an ArrayList to find an object with a certain field value通过 ArrayList 搜索以找到具有特定字段值的对象
【发布时间】:2016-12-08 19:06:03
【问题描述】:

我有一个数组列表 ArrayList 医生,其中存储了一些医生的详细信息。每个医生都有一个唯一的 id 字段。有没有办法在数组列表中搜索具有特定 ID 值的医生?

【问题讨论】:

  • 你能把你创建数组列表的代码贴出来吗?也许这些数据可以更好地结构化为字典?
  • 听起来你最好将数据存储在Map<String, Doctor> 中,这将是医生标识符到相应医生对象的映射。查找将变得优雅而有效。

标签: java search arraylist


【解决方案1】:

您可以像这样在 ArrayList 上使用流:

Optional<Doctor> getUniqueDoctorById(List<Doctor> list, String id) {

    return list.stream()
            .filter(doctor -> doctor.getId().equals(id))
            .findFirst(); 
}

在这里您可以看到流式传输列表并过滤所有医生 ID 等于您正在搜索的 ID 的医生。

【讨论】:

    【解决方案2】:

    试试这样的。

    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;
    }
    

    【讨论】:

    • 我想我会使用它,因为我了解它是如何工作的。谢谢大家。
    • 好的,但请。如果您对答案感到满意,请记得关闭此问题
    【解决方案3】:

    最简单,但可能不是最有效的解决方案,我假设您为所有字段设置了带有 setter/getter 的“医生”,否则您将使用 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;
    }
    

    【讨论】:

    • 是的,我使用了带有私有字段值的 getter 和 setter,所以我会使用 d.getId()。我的 id 值是 int 所以我会在 if 语句中使用 == 而不是 ".equals" 正确吗?
    • 是的,没错。 "==" 用于精确相等,如数值相等,而 .equals 用于比较两个字符串。
    猜你喜欢
    • 2016-11-02
    • 2016-02-10
    • 2012-11-23
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2021-12-12
    相关资源
    最近更新 更多