Appearance
Java 8 Distinct by property
To get a list of distinct objects based on a property in Java 8, you can filter the stream while tracking seen property values in a Set.
Here is an example of how you can get a list of distinct Person objects by their age property in Java 8:
java
import java.util.*;
import java.util.stream.Collectors;
class Person {
private String name;
private int age;
public Person(String name, int age) { this.name = name; this.age = age; }
public int getAge() { return age; }
@Override public String toString() { return name + "(" + age + ")"; }
}
public class Main {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25)
);
Set<Integer> seenAges = new HashSet<>();
List<Person> distinctPeople = people.stream()
.filter(p -> seenAges.add(p.getAge()))
.collect(Collectors.toList());
System.out.println(distinctPeople); // [Alice(25), Bob(30)]
}
}In this example, the people list contains three Person objects. A HashSet is used to track ages that have already been encountered. The filter() method keeps only the first occurrence of each age, effectively removing duplicate objects. Finally, the collect() method gathers the distinct Person objects into a list.
You can use a similar approach to get a list of distinct objects by any property.
I hope this helps! Let me know if you have any questions.