Java Stream.distinct()
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] } }
工作原理:
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] } }
工作原理:
使用數字的自然相等性進行比較(基於整數的 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'}] } }
說明:
相等性檢查:重寫 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] } }
這確保應用程式僅儲存唯一的名稱,而不需要手動檢查重複項。
最後的收穫:
distinct() 很簡單:它從流中刪除重複項。
對於基元或不可變類型:直接使用即可。
對於自訂物件:確保正確的 equals() 和 hashCode() 實作。
實用提示:用它來清理任何形式的重複資料(例如清單、使用者輸入、資料庫結果)。
以上是Java Stream.distinct()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

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

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

在使用IntelliJIDEAUltimate版本啟動Spring...

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...

在使用TKMyBatis進行數據庫查詢時,如何優雅地獲取實體類變量名以構建查詢條件,是一個常見的難題。本文將針...
