Java Stream.distinct()
The Stream.distinct() method in Java is used to filter out duplicate elements from a stream, ensuring that the resulting stream contains only unique elements. It works based on the equals() method of the objects in the stream.
This method is part of the Java Stream API introduced in Java 8 and is commonly used to handle collections or arrays with duplicate values.
Example 1: Removing Duplicates from a List of Strings
Imagine you have a list of names, and some names are repeated. You want a list of unique names.
import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // List of names with duplicates List<String> names = List.of("Alice", "Bob", "Alice", "Charlie", "Bob", "David"); // Use Stream.distinct() to remove duplicates List<String> uniqueNames = names.stream() .distinct() .collect(Collectors.toList()); System.out.println(uniqueNames); // Output: [Alice, Bob, Charlie, David] } }
How it works:
The distinct() method compares each name and keeps only the first occurrence of a duplicate.
Example 2: Removing Duplicates from a List of Numbers
Let’s take a list of numbers where duplicates exist and extract only the unique numbers.
import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // List of numbers with duplicates List<Integer> numbers = List.of(1, 2, 3, 2, 4, 3, 5); // Use Stream.distinct() to remove duplicates List<Integer> uniqueNumbers = numbers.stream() .distinct() .collect(Collectors.toList()); System.out.println(uniqueNumbers); // Output: [1, 2, 3, 4, 5] } }
How it works:
The numbers are compared using their natural equality (based on equals() for Integer), so duplicates are filtered out.
Example 3: Working with Simple Objects
Let’s create a class Product and remove duplicates based on the product's id.
Code:
import java.util.List; import java.util.Objects; import java.util.stream.Collectors; class Product { private int id; private String name; public Product(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return id == product.id; } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "Product{id=" + id + ", name='" + name + "'}"; } } public class Main { public static void main(String[] args) { // List of products with duplicates (based on id) List<Product> products = List.of( new Product(1, "Laptop"), new Product(2, "Tablet"), new Product(1, "Laptop"), // Duplicate new Product(3, "Smartphone"), new Product(2, "Tablet") // Duplicate ); // Use Stream.distinct() to remove duplicates List<Product> uniqueProducts = products.stream() .distinct() .collect(Collectors.toList()); System.out.println(uniqueProducts); // Output: // [Product{id=1, name='Laptop'}, Product{id=2, name='Tablet'}, Product{id=3, name='Smartphone'}] } }
Explanation:
Equality Check: The equals() method is overridden to ensure Product objects are considered equal based on their id.
Duplicate Removal: When distinct() encounters two products with the same id, it keeps only the first one.
Output: You get a list of unique products.
Simplified Understanding
- For Primitive or Simple Objects (like Integer, String):
distinct() removes duplicates by comparing values directly.
Example: [1, 2, 2, 3] becomes [1, 2, 3].
- For Custom Objects:
You need to implement the equals() and hashCode() methods for the class.
distinct() uses these methods to determine if two objects are duplicates.
Use Case: Filtering Duplicate Names from User Input
Imagine a user enters names repeatedly in a form, and you want to ensure only unique names are stored.
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // Simulate user input List<String> userInput = new ArrayList<>(); userInput.add("John"); userInput.add("Mary"); userInput.add("John"); // Duplicate userInput.add("Alice"); // Remove duplicates List<String> uniqueInput = userInput.stream() .distinct() .collect(Collectors.toList()); System.out.println(uniqueInput); // Output: [John, Mary, Alice] } }
This ensures that the application only stores unique names without requiring manual checks for duplicates.
Final Takeaway:
distinct() is simple: it removes duplicates from a stream.
For primitives or immutable types: Just use it directly.
For custom objects: Ensure proper equals() and hashCode() implementations.
Practical Tip: Use it to clean up duplicate data in any form (e.g., lists, user inputs, database results).
The above is the detailed content of Java Stream.distinct(). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Start Spring using IntelliJIDEAUltimate version...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...
