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
Syntax
stream.distinct()
Return value
A new Stream<T>.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
stream.sorted()· Return a stream sorted by natural order or by a Comparator. The source collection is not changed.stream.count()· Return the number of elements in the stream (a long). A terminal operation.- Java Streams · tutorial