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
Table of contents
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.
1 2 3 4 5 6 7 8 9 |
List<String> list = Arrays.asList("A", "B", "A", "C", "D", "B"); // Getting duplicate elements List<String> distinctElements = list.stream() .distinct() .collect(Collectors.toList()); System.out.println(distinctElements); // Output = [A, B, C, D] |
Remove duplicate Object elements
Let’s take now an example of a list of Object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
public class JavaStreamDistinctExample { public static void main(String[] args) { List<Order> orders = new ArrayList<>(); orders.add(new Order(1, 100)); orders.add(new Order(2, 200)); orders.add(new Order(3, 300)); orders.add(new Order(4, 400)); orders.add(new Order(2, 250)); orders.add(new Order(1, 150)); List<Order> distinctOrders = orders.stream() .distinct() .collect(Collectors.toList()); System.out.println("Distinct orders = " + distinctOrders); // Output : Distinct orders = [Order{id=1, price=100}, Order{id=2, price=200}, Order{id=3, price=300}, Order{id=4, price=400}] } } class Order { private int id; private int price; Order(int id, int price) { this.id = id; this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Order order = (Order) o; return id == order.id; } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "Order{" + "id=" + id + ", price=" + price + '}'; } } |
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Â