Home Java javaTutorial Java Stream.distinct()

Java Stream.distinct()

Nov 26, 2024 pm 03:09 PM

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]
    }
}

Copy after login

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]
    }
}

Copy after login

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'}]
    }
}

Copy after login

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

  1. For Primitive or Simple Objects (like Integer, String):

distinct() removes duplicates by comparing values directly.

Example: [1, 2, 2, 3] becomes [1, 2, 3].

  1. 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]
    }
}

Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

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. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

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...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

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...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

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

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

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...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

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...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

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...

See all articles