204. Implementing distinctBy() for the Stream API
Let’s suppose that we have the following model and data:
public class Car { private final String brand; private final String fuel; private final int horsepower; ... } List<Car> cars = List.of( new Car("Chevrolet", "diesel", 350), ... new Car("Lexus", "diesel", 300) ); We know that the Stream API contains the distinct() intermediate operation, which is capable of keeping only the distinct elements based on the equals() method:
cars.stream() .distinct() .forEach(System.out::println); While this code prints the distinct cars, we may want a distinctBy() intermediate operation that is capable of keeping only the distinct elements based on a given property/key. For instance, we may need all the cars distinct by brand. For this, we can rely on the toMap() collector and the identity function, as follows:
cars.stream() .collect(Collectors.toMap...