Home > Java > javaTutorial > Java Stream.distinct()

Java Stream.distinct()

Mary-Kate Olsen
Release: 2024-11-26 15:09:09
Original
808 people have browsed it

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!

source:dev.to
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template