过滤具有类似数据的ArrayList

时间:2022-01-10 20:45:13

I have the following classes:

我有以下课程:

public class School{
List<ClassRoom> classRooms;
}

public class ClassRoom{
List<Student> students;
}

public class Student{
String name;
long typeId;
}

I need to get the whole students within the given class roomS that has typeID=123

我需要让整个学生都在给定的类室ID中,类型ID = 123

Expected result:

List filteredStudent=classRoomList.filterByStudentTypeID(typeIdToSearchFor)

I don't need to write some dirty code and loops.

我不需要编写一些脏代码和循环。

I need to take advantage of existing libraries. I found out Google Guava.

我需要利用现有的库。我发现了谷歌番石榴。

I found out a method at guava that searches by the the whole reference ... instead I need to search using the attribute, typeId

我在guava上发现了一个按整个引用搜索的方法...而不是我需要使用属性typeId进行搜索

Collection<Student> filtered =Collections2.filter(students, Predicates.equalTo(s1));

Any ideas!

1 个解决方案

#1


2  

Since you are using Guava, you can use a custom predicate:

由于您使用的是Guava,因此您可以使用自定义谓词:

final long typeIdToSearchFor = ...;
Collection<Student> filtered = Collections2.filter(students,
    new Predicate<Student>() {
        @Override
        public boolean apply(Student s) {
            return s.typeId == typeIdToSearchFor;
        }
    }
);

Note that typeIdToSearchFor must be final in the scope of the call to filter because it is being referenced by the (anonymous) Predicate subclass.

请注意,typeIdToSearchFor必须在调用过滤器的范围内是最终的,因为它是由(匿名)Predicate子类引用的。

#1


2  

Since you are using Guava, you can use a custom predicate:

由于您使用的是Guava,因此您可以使用自定义谓词:

final long typeIdToSearchFor = ...;
Collection<Student> filtered = Collections2.filter(students,
    new Predicate<Student>() {
        @Override
        public boolean apply(Student s) {
            return s.typeId == typeIdToSearchFor;
        }
    }
);

Note that typeIdToSearchFor must be final in the scope of the call to filter because it is being referenced by the (anonymous) Predicate subclass.

请注意,typeIdToSearchFor必须在调用过滤器的范围内是最终的,因为它是由(匿名)Predicate子类引用的。