When working with Iterable in Java, sometimes you need to remove duplicated elements before processing them. Java provides a powerful Stream API to perform that. This tutorials shows some Java Stream Distinct to remove duplicates examples.

Important to know :

  • The elements are compared using the equals() method.
  • The order is preserved if the stream is ordered. For unordered streams, no stability guarantees are made.
  • Preserving stability for distinct() in parallel pipelines is relatively expensive

Remove duplicate basic elements

In this example, we will take a list of basic elements (string) and retrieve all distinct elements using distinct() stream function.

Remove duplicate Object elements

Let’s take now an example of a list of Object.

Java Stream API uses both equals() and hashCode() methods to check if two objects equality.

Java Stream distinct by property

This tutorial shows how to use distinct by object property instead of equals