I have two Lists containing objects of this class:
public class ClassObj {
private Integer Id;
private List<String> students;
}
I want to compare the objects in those two lists by students. I have to compare the lists and get data lijke below
- I need to create a new List containing those
ClassObj
objects which are present inlist1
but not inlist2
- I need to create a new List containing those
ClassObj
objects which are present inlist2
but not inlist1
- I need to create a new List containing those
ClassObj
objects which are present in both the lists using java8 streams
I tried with the below code
List<ClassObj> prevYearList = getPrevYearData(id);
List<ClassObj> currYearList = getCurrentYearData(id);
To find students who got TC (exists in list 1 but not in list2)
List<ClassObj> studentsGotTC = prevYearList.stream()
.filter(curr -> (currYearList.stream().filter(prev -> prev.getStudents().equals(curr.getStudents()))
.count()) < 1)
.collect(Collectors.toList());
To find new Admission (exists in list2 but not in list1)
List<ClassObj> newAdmission = currYearList.stream()
.filter(prev -> (prevYearList.stream()
.filter(curr -> prev.getStudents().equals(curr.getStudents())).count()) < 1)
.collect(Collectors.toList());
To find Students continuing in the school (exists in both list)
List<List<String>> studentsList = studentsGotTC.parallelStream()
.map(ClassObj::getStudents)
.collect(Collectors.toList());
List<ClassObj> existingStudents = prevYearList.stream()
.filter(e -> !studentsList.contains(e.getStudents()))
.collect(Collectors.toList());
It is returning me the results properly but i dont want to go through two streams and filter data, how to optimize the above code efficiently. i.e., by using single stream