Java 中的 Stream.distinct() 方法用於從流中過濾掉重複元素,確保產生的流僅包含唯一元素。它基於流中物件的 equals() 方法工作。
此方法是 Java 8 中引入的 Java Stream API 的一部分,通常用於處理具有重複值的集合或陣列。
範例 1:從字串清單中刪除重複項目
想像一下你有一個名字列表,其中一些名字是重複的。您想要一個唯一名稱的清單。
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>
工作原理:
distinct() 方法比較每個名稱並僅保留第一次出現的重複項。
範例 2:從數字清單中刪除重複項
讓我們列出存在重複的數字並僅提取唯一的數字。
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>
工作原理:
使用數字的自然相等性進行比較(基於整數的 equals()),因此重複項會被過濾掉。
範例 3:使用簡單物件
讓我們建立一個 Product 類別並根據產品的 id 刪除重複項。
代碼:
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>
說明:
相等性檢查:重寫 equals() 方法以確保 Product 物件根據其 id 被視為相等。
去重:當distinct()遇到兩個相同id的產品時,只保留第一個。
輸出:您獲得獨特產品的清單。
簡化理解
- 對於原始或簡單物件(如整數、字串):
distinct() 透過直接比較值來刪除重複項。
例:[1, 2, 2, 3] 變成 [1, 2, 3]。
- 對於自訂物件:
您需要為類別實作 equals() 和 hashCode() 方法。
distinct() 使用這些方法來確定兩個物件是否重複。
用例:過濾使用者輸入中的重複名稱
想像一下,使用者在表單中重複輸入名稱,並且您希望確保僅儲存唯一的名稱。
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>
這確保應用程式僅儲存唯一的名稱,而不需要手動檢查重複項。
最後的收穫:
distinct() 很簡單:它從流中刪除重複項。
對於基元或不可變類型:直接使用即可。
對於自訂物件:確保正確的 equals() 和 hashCode() 實作。
實用提示:用它來清理任何形式的重複資料(例如清單、使用者輸入、資料庫結果)。
以上是Java Stream.distinct()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

記事本++7.3.1
好用且免費的程式碼編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。