【问题标题】:Check if an array of objects with a specific property - java [duplicate]检查具有特定属性的对象数组 - java [重复]
【发布时间】:2020-12-17 20:30:54
【问题描述】:

我有一个充满对象的数组列表,我想检查是否有 name 属性等于“maths”的对象。

如何做到这一点?

if(courses.contains(students.get(i).chosenPathway)){

现在我正在使用它,但它不起作用,因为课程是对象的数组列表

【问题讨论】:

    标签: java


    【解决方案1】:

    下次你应该添加更多关于变量名称的信息,但我想我能明白你的意思。 您需要检查列表中的每个对象属性并将其与 equals 进行比较,例如:

    
    for (int i = 0; i < courses.size(); i++) {
    if (courses.get(i).chosenPathway().equalsIgnoreCase("maths")) {
    System.out.println("An object contains maths as chosen pathway.");
    break;
    }
    
    }
    
    
    

    【讨论】:

    • 别忘了给@guynumerouno 投票:D
    • 最好使用equalsIgnoreCase 以不区分大小写的方式进行匹配。
    【解决方案2】:

    遍历数组,然后按照你的逻辑。我假设Course 包含一个名为students 的列表,您需要从中知道他们的chosenPathWay 是否是“数学”。

    yourArray 是包含所有课程的数组。

    List<Student> matchingStudents=new ArrayList<Student>();
    
    for (int i=0;i<yourArray.length();i++)
    {
       Course c = yourArray[i];
       for (Student student: c.students)
          if (student.chosenPathway.equalsIgnoreCase(requiredPath)) //requiredPath = "maths"
              matchingStudents.add(student);
    
    }
    

    上面的代码假定您必须存储所有符合条件的学生。如果您只需要知道课程中是否有学生学习数学,只需:

    List<Course> matchingCourses =new ArrayList<>();
    
    for (int i=0;i<yourArray.length();i++)
    {
       Course c = yourArray[i];
       for (Student student: c.students)
          if (student.chosenPathway.equalsIgnoreCase(requiredPath)) //requiredPath="maths"
          {   
             matchingCourses.add(c);
             break;                  //finish looping through this course
           }
     }
    

    【讨论】:

    • aran - 好答案。几点:(1)在第二种解决方案中,您不需要ListString 变量足以存储第一个匹配值。 (2) 您也可以使用Stream API 添加解决方案。
    • 第二个列表是不必要的,您说得对。但是关于您的第二点,我只是讨厌 Streams ; ) 这是个人的事情
    • aran - 哈哈 ...Stream 还不错:)
    • 真的,我讨厌它。和我的治疗师一起工作。问@Stephen C,他知道 --> stackoverflow.com/a/65164081/2148953
    【解决方案3】:

    假设您有一个如下列表

    List<Student> studentsList = new ArrayList<>();
    

    在 Java-8 之前

    for(Student stud : StudentList){
       if("maths".equals(stud.getChosenPathway())){
        //your logic goes here
        }
    }
    

    Java-8 及以上版本

    获取单个对象

    Optional<Student> stud = studentList.stream().findFirst().filter(s -> s.getChosenPathway().equals("maths"));
    

    获取所有对象

    List<Student> empl = studentsList.stream().filter(s -> s.getName().equals("maths")).collect(Collectors.toList());
    

    【讨论】:

    • 正确的方法是: Optional stud = studentList.stream().filter(s -> s.getChosenPathway().equals("maths")).findFirst();你为什么把 findFirst() 放在首位?这样你过滤只会找到一个元素
    猜你喜欢
    • 2017-10-09
    • 2012-11-12
    • 2013-12-26
    • 2020-06-08
    • 2015-08-24
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多