筛选刚刚有交叉数据的ArrayList

筛选刚刚有交叉数据的ArrayList

我有以下课程:

public class School{
    List<ClassRoom> classRooms;
}

public class ClassRoom{
    List<Student> students;
}

public class Student{
    String name;
    List<Long> typeIdList;
}


我只需要得到typeId,它们是给定教室S中所有学生之间的共同因素。

为了使给定类型ID = 123的给定教室S中的所有学生,我执行以下操作:

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


只想知道番石榴是否可以处理类似的事情?
通过交集,我的意思是必须在所有情况下都考虑这种类型。

我知道for循环将更具可读性,但我只是发现了Guava功能。

最佳答案

您可以使用Multiset来计算出现次数:

ClassRoom classRoom = /* comes from somewhere */;
List<Student> students = classRoom.getStudents();

// Aggregate all the typeIds.
Multiset<Long> typeIds = HashMultiset.create();
for (Student student : students) {
    // Assuming a student doesn't have duplicated typeIds:
    typeIds.addAll(student.getTypeIds());
}

// Find which typeIds are present for all the students.
for (Multiset.Entry<Long> entry : typeIds.entrySet()) {
    if (entry.getCount() == students.size()) {
        System.out.println(entry.getElement());
    }
}

关于java - 筛选刚刚有交叉数据的ArrayList,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16147505/

10-11 16:59