Java 25 (LTS) reference · Stream API

Java Stream distinct() Method

Remove duplicate elements (by equals()), keeping the first occurrence of each, in encounter order.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

stream.distinct()

Return value

A new Stream<T>.

Examples

Remove duplicates
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(Stream.of(3, 1, 3, 2, 1).distinct().toList());
    }
}

Output

[3, 1, 2]

Run this on your computer — see “Get Started” for setup.

Distinct after normalising
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(Stream.of("Ana", "ana", "Ben").map(String::toLowerCase).distinct().count());
    }
}

Output

2

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?