Skip to main content
deleted 1 character in body
Source Link
Rumid
  • 1.7k
  • 3
  • 21
  • 43

You can use a different approach with streams. Eg:

List<Student> allStudentsA = assignStudents(); List<Student> duplicateStudents = allStudents.stream() .collect(groupingBy(Student::getId)) //Now you've got Map<String, List<Student>> (assuming id is of type String). //Id of an user is a key. In value (list) you have all Students with the same id. //Now we want to take this lists, which have size greater than two and merge them. .values() .stream() .filter(list -> list.size() >= 2) .flatMap(List::stream) .collect(Collectors.toList()); 

(Improvements are welcome.)

You can use a different approach with streams. Eg:

List<Student> allStudentsA = assignStudents(); List<Student> duplicateStudents = allStudents.stream() .collect(groupingBy(Student::getId)) //Now you've got Map<String, List<Student>> (assuming id is of type String). //Id of an user is a key. In value (list) you have all Students with the same id. //Now we want to take this lists, which have size greater than two and merge them. .values() .stream() .filter(list -> list.size() >= 2) .flatMap(List::stream) .collect(Collectors.toList()); 

(Improvements are welcome.)

You can use a different approach with streams. Eg:

List<Student> allStudentsA = assignStudents(); List<Student> duplicateStudents = allStudents.stream() .collect(groupingBy(Student::getId)) //Now you've got Map<String, List<Student>> (assuming id is of type String). //Id of an user is a key. In value (list) you have all Students with the same id. //Now we want to take this lists which have size greater than two and merge them. .values() .stream() .filter(list -> list.size() >= 2) .flatMap(List::stream) .collect(Collectors.toList()); 

(Improvements are welcome.)

Source Link
Rumid
  • 1.7k
  • 3
  • 21
  • 43

You can use a different approach with streams. Eg:

List<Student> allStudentsA = assignStudents(); List<Student> duplicateStudents = allStudents.stream() .collect(groupingBy(Student::getId)) //Now you've got Map<String, List<Student>> (assuming id is of type String). //Id of an user is a key. In value (list) you have all Students with the same id. //Now we want to take this lists, which have size greater than two and merge them. .values() .stream() .filter(list -> list.size() >= 2) .flatMap(List::stream) .collect(Collectors.toList()); 

(Improvements are welcome.)