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] } } </string></string>
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] } } </integer></integer>
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'}] } } </product></product>
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] } } </string></string>
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!

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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