00:00

Java Stream distinct() Method

Last updated:

distinct() is a stateful intermediate operation of java.util.stream.Stream, available since Java 8, that returns a stream with duplicate elements removed. Two elements are duplicates when equals() says so, so the result depends on how the element type implements equals() and hashCode().

This tutorial explains which occurrence is kept, how distinct() treats records, custom classes and null, how to remove duplicates by a property instead of the whole object, and what it costs in memory and in parallel streams.

1. Syntax and Method Signature

Stream.java (API)
// java.util.stream.Stream<T> (Java 8)
Stream<T> distinct()

// primitive versions
IntStream    IntStream.distinct()
LongStream   LongStream.distinct()
DoubleStream DoubleStream.distinct()

distinct() takes no arguments and returns a Stream<T> of the same type. It uses no functional interface; equality comes from the elements' own equals() and hashCode() methods.

Usage
List<String> uniqueCities = visits.stream().distinct().toList();

2. How distinct() Works

As elements flow through, distinct() remembers every value it has already passed on, in a hash-based set in the JDK implementation. When an element arrives, it is passed on only if an equal element has not been seen before. This makes it stateful: memory grows with the number of distinct values.

  • Ordered streams: the first occurrence is kept and the result keeps encounter order. The operation is stable.
  • Unordered streams: any one of the equal elements may be kept, and there are no order guarantees.
  • Already distinct sources: if the source reports the DISTINCT characteristic, as a Set does, the step can be skipped.
  • Parallel: keeping the first occurrence in an ordered parallel stream needs extra coordination and buffering; calling unordered() first makes it cheaper when order does not matter.
distinct() keeps the first occurrence of each value The values Goa, Pune, Goa, Agra, Pune and Goa pass through distinct. The first Goa, the first Pune and Agra are kept; the later repeats are dropped. The result is Goa, Pune, Agra in first-seen order. VISITS Goa Pune Goa Agra Pune Goa distinct() UNIQUE Goa Pune Agra
Figure 1: On an ordered stream, the first occurrence of each value is kept (green) and later repeats are dropped (red), so the result keeps first-seen order.

3. Java Examples

Example 1: Removing duplicate strings and numbers (Java 9+)

Remove repeated city names from a travel history and repeated error codes from a log.

RemoveDuplicates.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class RemoveDuplicates {

    public static void main(String[] args) {
        List<String> visits = List.of("Goa", "Pune", "Goa", "Agra", "Pune", "Goa");
        List<String> cities = visits.stream().distinct().collect(Collectors.toList());
        System.out.println("Cities: " + cities);

        int[] errorCodes = {404, 500, 404, 503, 500};
        System.out.println("Unique codes: " + IntStream.of(errorCodes).distinct().count());
    }
}
Output
Cities: [Goa, Pune, Agra]
Unique codes: 3

How it works: String and Integer implement equals() by value, so equal values are treated as duplicates. The first occurrence wins, which keeps the list in first-visited order.

Example 2: Records compare by value (Java 16+)

A shopping cart may contain the same product line twice. Records get value-based equals() automatically.

DistinctRecords.java
import java.util.List;

public class DistinctRecords {

    record CartLine(String sku, int qty) { }

    public static void main(String[] args) {
        List<CartLine> lines = List.of(
                new CartLine("SKU-1", 2),
                new CartLine("SKU-2", 1),
                new CartLine("SKU-1", 2),
                new CartLine("SKU-1", 5));

        List<CartLine> unique = lines.stream().distinct().toList();

        unique.forEach(System.out::println);
    }
}
Output
CartLine[sku=SKU-1, qty=2]
CartLine[sku=SKU-2, qty=1]
CartLine[sku=SKU-1, qty=5]

How it works: The two SKU-1, 2 lines are equal in every component, so one is dropped. SKU-1, 5 differs in quantity and stays. A plain class without equals() and hashCode() would compare by identity, and no line would be removed.

Example 3: Distinct by a property (Java 16+)

Keep one customer per email address, preferring the first record seen, even when the names differ in case.

DistinctByEmail.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DistinctByEmail {

    record Customer(String name, String email) { }

    public static void main(String[] args) {
        List<Customer> imported = List.of(
                new Customer("Anil", "anil@mail.in"),
                new Customer("Bela", "bela@mail.in"),
                new Customer("ANIL K", "Anil@mail.in"),
                new Customer("Chen", "chen@mail.in"));

        Map<String, Customer> byEmail = imported.stream()
                .collect(Collectors.toMap(
                        c -> c.email().toLowerCase(),
                        Function.identity(),
                        (first, duplicate) -> first,
                        LinkedHashMap::new));

        List<Customer> unique = new ArrayList<>(byEmail.values());
        unique.forEach(c -> System.out.println(c.name() + " <" + c.email() + ">"));
    }
}
Output
Anil <anil@mail.in>
Bela <bela@mail.in>
Chen <chen@mail.in>

How it works: distinct() always uses the whole object's equals(). To deduplicate by one property, key a map by that property and keep the first value in the merge function. LinkedHashMap preserves first-seen order.

Example 4: distinct() after a transformation (Java 16+)

List the distinct domains of a mailing list, in alphabetical order.

DistinctDomains.java
import java.util.List;

public class DistinctDomains {

    public static void main(String[] args) {
        List<String> emails = List.of(
                "a@zoho.com", "b@gmail.com", "c@zoho.com", "d@outlook.com", "e@gmail.com");

        List<String> domains = emails.stream()
                .map(email -> email.substring(email.indexOf('@') + 1))
                .distinct()
                .sorted()
                .toList();

        System.out.println(domains);
    }
}
Output
[gmail.com, outlook.com, zoho.com]

How it works: Mapping first and then calling distinct() removes duplicates of the derived value. Calling distinct() before sorted() means the sort handles three values instead of five.

4. Real-World Use Cases

  • Clean imports: remove repeated rows from CSV or API data before saving.
  • Unique dimensions: list the distinct categories, regions or tags present in a data set for a filter drop-down.
  • Deduplicated notifications: notify each affected user once even if they appear in several groups.

5. Important Points

  • Empty streams stay empty.
  • Null is allowed: one null element is kept and repeated nulls are removed.
  • Equality rules: classes without overridden equals() and hashCode() are compared by identity.
  • Mutable elements: changing an element's fields after it has been seen can break the hash lookup; use immutable elements.
  • Memory: every distinct value is remembered until the stream ends, so very large or infinite streams with many distinct values can exhaust memory.
  • Case and formatting: "Goa" and "goa" are different; normalise with map() first.

6. distinct() vs Other Ways to Deduplicate

ApproachKeeps orderDedupes byResult
stream().distinct()Yes (first occurrence)Whole elementA stream
collect(Collectors.toSet())NoWhole elementA Set
new LinkedHashSet<>(list)YesWhole elementA Set
toMap(key, identity(), (a, b) -> a)With LinkedHashMapA chosen propertyA Map
groupingBy(key)With LinkedHashMapA chosen property, keeps allA Map of lists

See Find Duplicate Elements for finding the duplicates themselves rather than removing them.

7. Common Mistakes and Best Practices

Expecting distinct() to use a custom rule

distinct() has no parameter, so it cannot compare by name or ignore case. Normalise first or use a map keyed by the property, as in Example 3.

Forgetting equals() and hashCode() in a class

EqualsMatters.java
import java.util.List;
import java.util.Objects;

public class EqualsMatters {

    static final class Point {
        final int x, y;
        Point(int x, int y) { this.x = x; this.y = y; }

        @Override public boolean equals(Object o) {
            return o instanceof Point p && p.x == x && p.y == y;
        }

        @Override public int hashCode() {
            return Objects.hash(x, y);
        }
    }

    public static void main(String[] args) {
        long unique = List.of(new Point(1, 2), new Point(1, 2), new Point(3, 4)).stream()
                .distinct()
                .count();
        System.out.println("Distinct points: " + unique);
    }
}
Output
Distinct points: 2

Remove the two overridden methods and the output becomes 3, because every new Point is a different object.

Other mistakes to avoid

  • Calling distinct() on an infinite stream with endless new values without limit().
  • Sorting before deduplicating. Run distinct() first so sorted() has less to do.
  • Using a Set when order matters. HashSet loses order; distinct() or LinkedHashSet keep it.

8. Summary

  • distinct() removes duplicates based on equals() and hashCode().
  • On ordered streams it keeps the first occurrence and preserves order.
  • It is stateful and remembers every distinct value, so memory grows with uniqueness.
  • To deduplicate by a property, use toMap() with a merge function and a LinkedHashMap.

9. References