检查具有特定属性的对象数组是否为java

检查具有特定属性的对象数组是否为java,java,Java,我有一个充满对象的数组列表,我想检查是否有任何对象的名称属性等于“数学” 如何做到这一点 if(courses.contains(students.get(i).chosenPathway)){ 现在我正在使用这个,但它不起作用,因为它是一个对象数组列表下次你应该添加更多关于变量名称的信息,但我想我可以理解你的意思。 您需要检查列表中的每个对象属性,并将其与equals进行比较,例如: for (int i = 0; i < courses.size(); i++) { if (cou

我有一个充满对象的数组列表,我想检查是否有任何对象的名称属性等于“数学”

如何做到这一点

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

现在我正在使用这个,但它不起作用,因为它是一个对象数组列表

下次你应该添加更多关于变量名称的信息,但我想我可以理解你的意思。 您需要检查列表中的每个对象属性,并将其与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;
}

}



对于(int i=0;i
在阵列中循环,然后按照您的逻辑进行操作。我假设
课程
包含一个名为
学生
的列表,您需要从中了解他们的
选择路径
是否为“数学”

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 matchingStudents=new ArrayList();

对于(int i=0;i假设您有一个如下列表

List<Student> studentsList = new ArrayList<>();
使用Java-8及以上版本

获取单个对象

Optional<Student> stud = studentList.stream().findFirst().filter(s -> s.getChosenPathway().equals("maths"));
Optional stud=studentList.stream().findFirst().filter(s->s.getChosenPathways().equals(“数学”);
获取所有对象

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

谢谢你,先生!这很有帮助不要忘了投票@guynumeuno:d最好使用
equalsIgnoreCase
以不区分大小写的方式进行匹配。aran-回答得好。有两点:(1)在第二种解决方案中,你不需要
列表
,一个
字符串
变量就足以存储第一个匹配值。(2)您还可以使用
API添加解决方案。您认为第二个列表不必要是对的。但是关于您的第二点,我只是讨厌流;)这是一件个人的事情。哈哈…
还不错:)真的,我讨厌它。和我的治疗师一起工作。问@Stephen C,他知道-->
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());