To get the distinct elements of a list or stream based on a specific key in Java, you can use the distinct() method from the java.util.stream package and the Collectors.toMap() method to create a map with the key as the key and the element as the value.
Here's an example of how to do this using a list:
import java.util.List;
import java.util.stream.Collectors;
// Sample list of objects with a name and age field
List<Person> people = List.of(
new Person("Alice", 20),
new Person("Bob", 25),
new Person("Charlie", 30),
new Person("Alice", 20)
);
// Use the distinct() method and Collectors.toMap() to create a map of distinct names to people
Map<String, Person> distinctPeople = people.stream()
.collect(Collectors.toMap(
person -> person.getName(), // Key is the name
person -> person, // Value is the person object
(p1, p2) -> p1 // If a duplicate key is encountered, keep the first value
));
// Print the distinct names and corresponding people
distinctPeople.forEach((name, person) -> System.out.println(name + ": " + person));
This will output the following:
Alice: Person{name='Alice', age=20}
Bob: Person{name='Bob', age=25}
Charlie: Person{name='Charlie', age=30}