Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

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...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard