In java 8 we cannot filter same field’s object directly.
For example:
Student dart = new Student(“dart”, 20);
Student vecna = new Student(“vecna”, 30);
Student luba = new Student("luba", 20);
If I wanna filter student with identical age. It’s hard to filter without 2 for loop.
Using Java Stream filter with predicate is a good choice to resolve this issue.
First create Java predicate function
public static <T> Predicate<T> distinctBy(Function<? super T, ?> f) {
Set<Object> objects = new HashSet<>();
return t -> objects.add(f.apply(t));
}
Then filter the identical age student.
Set<Student> students = students
.stream()
.filter(distinctBy(Student::age))
.collect(Collectors.toSet()));System.out.println(students);
After that, we should only get these answer.
[{"dart", 20}, {"luba", 30}]
Reference: