Java Stream distinct() Method
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
// 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.
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
DISTINCTcharacteristic, as aSetdoes, 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.
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.
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());
}
}
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.
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);
}
}
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.
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() + ">"));
}
}
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.
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);
}
}
[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
nullelement is kept and repeated nulls are removed. - Equality rules: classes without overridden
equals()andhashCode()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 withmap()first.
6. distinct() vs Other Ways to Deduplicate
| Approach | Keeps order | Dedupes by | Result |
|---|---|---|---|
stream().distinct() | Yes (first occurrence) | Whole element | A stream |
collect(Collectors.toSet()) | No | Whole element | A Set |
new LinkedHashSet<>(list) | Yes | Whole element | A Set |
toMap(key, identity(), (a, b) -> a) | With LinkedHashMap | A chosen property | A Map |
groupingBy(key) | With LinkedHashMap | A chosen property, keeps all | A 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
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);
}
}
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 withoutlimit(). - Sorting before deduplicating. Run
distinct()first sosorted()has less to do. - Using a
Setwhen order matters.HashSetloses order;distinct()orLinkedHashSetkeep it.
8. Summary
distinct()removes duplicates based onequals()andhashCode().- 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 aLinkedHashMap.
9. References
Frequently Asked Questions (FAQ)
Q1. How does distinct() decide that two elements are duplicates?
It uses the elements' equals() method, together with hashCode() in the JDK's hash-based implementation. Strings, numbers and records compare by value; classes that do not override equals() compare by identity.
Q2. Which occurrence does distinct() keep?
For an ordered stream, it keeps the first occurrence and preserves encounter order. For an unordered stream, it may keep any one of the equal elements.
Q3. Can distinct() remove duplicates by a field?
No. distinct() compares whole elements. To deduplicate by a field, collect with Collectors.toMap(field, Function.identity(), (a, b) -> a, LinkedHashMap::new) and take the values, or map to the field first if you only need the field.
Q4. Does distinct() work with null elements?
Yes. A null element is kept once and further nulls are removed.
Q5. Is distinct() expensive?
It is stateful: it must remember every distinct value it has seen, so memory grows with the number of unique elements. In ordered parallel streams it also needs buffering; call unordered() first if order does not matter.