Java Stream filter duplicate Object field.

Even
Jul 6, 2022

--

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:

collections — Java 8 Distinct by property — Stack Overflow

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response