Java 8 Distinct by property
To get a list of distinct elements by a property in Java 8, you can use the
distinct() method of the
Stream interface and the
map() method to extract the property from each element.
Here is an example of how you can get a list of distinct elements by a property in Java 8:
List<Person> people = Arrays.asList( new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 25) ); List<Integer> ages = people.stream() .map(Person::getAge) .distinct() .collect(Collectors.toList()); System.out.println(ages); // [25, 30]
In this example, the
people list contains three
Person objects. The
map() method is used to extract the
age property from each
Person object and the
distinct() method is used to remove duplicate ages. Finally, the
collect() method is used to collect the distinct ages into a list.
You can use a similar approach to get a list of distinct elements by any property of an object.
I hope this helps! Let me know if you have any questions.