Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
IT NachrichtenLG Display: Erstes 720-Hz-OLED-Panel vorgestellt(21.09.2026 um 13:30 Uhr)
IT NachrichtenLG Display: Erstes 720-Hz-OLED-Panel vorgestellt(21.09.2026 um 13:30 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

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…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

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




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







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

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Java Stream.distinct()

Thematisch verwandte Begriffe: Java, Streamdistinct · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-94142 | A security vulnerability has been detected in BioStar Temperature Monito…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick