【发布时间】:2020-12-17 20:30:54
【问题描述】:
我有一个充满对象的数组列表,我想检查是否有 name 属性等于“maths”的对象。
如何做到这一点?
if(courses.contains(students.get(i).chosenPathway)){
现在我正在使用它,但它不起作用,因为课程是对象的数组列表
【问题讨论】:
标签: java
我有一个充满对象的数组列表,我想检查是否有 name 属性等于“maths”的对象。
如何做到这一点?
if(courses.contains(students.get(i).chosenPathway)){
现在我正在使用它,但它不起作用,因为课程是对象的数组列表
【问题讨论】:
标签: java
下次你应该添加更多关于变量名称的信息,但我想我能明白你的意思。 您需要检查列表中的每个对象属性并将其与 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;
}
}
【讨论】:
equalsIgnoreCase 以不区分大小写的方式进行匹配。
遍历数组,然后按照你的逻辑。我假设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
}
}
【讨论】:
List,String 变量足以存储第一个匹配值。 (2) 您也可以使用Stream API 添加解决方案。
Stream 还不错:)
假设您有一个如下列表
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());
【讨论】: