一、distinct()方法介紹
在Java 8中,Stream介面是一個完全支持函數式編程風格的介面。在Stream中,distinct()方法可以實現對流中元素的去重,返回一個保證元素唯一的新流。
distinct()方法使用時需要注意以下幾點:
- 元素需實現equals()和hashCode()方法,否則去重不生效
- 對於流中具有null值的元素,需要使用Objects.hashCode()進行判定
二、使用場景
Stream().distinct()方法適用於需要從數據集中獲得唯一元素的場景,例如:
- 從資料庫查詢結果中獲取不同的值
- 從文件讀取中獲取不同的單詞或行
- 對列表中的元素進行去重
三、實現方法
下面是一個簡單的使用stream().distinct()方法對列表元素進行去重的例子:
List numbers = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 5, 6); List distinctNumbers = numbers.stream().distinct().collect(Collectors.toList()); System.out.println(distinctNumbers);
輸出結果:
[1, 2, 3, 4, 5, 6]
可以看出,去重後的列表中只剩下了不同的元素。
四、元素去重的實現原理
Stream().distinct()方法的去重原理是:
- 在元素流中,對每個元素進行hashCode()方法的計算
- 將不同hashCode的元素加入新的HashSet集合中。
- 返回加入HashSet集合的新元素流
五、重寫equals()和hashCode()方法
對於一個類的對象如果想要使用distinct()去重,則要求該類的對象需要重寫equals()和hashCode()方法。
下面是一個例子:
class Person { private Integer id; private String name; public Person(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return Objects.equals(id, person.id) && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(id, name); } } List personList = Arrays.asList( new Person(1, "Tom"), new Person(2, "Jerry"), new Person(3, "Tom") ); List distinctPersons = personList.stream().distinct().collect(Collectors.toList()); System.out.println(distinctPersons);
輸出結果:
[Person(id=1, name=Tom), Person(id=2, name=Jerry)]
可以看出,使用distinct()方法後,列表中重複的”Tom”被成功去除,只保留了不同的元素。
六、使用forEach()方法輸出流中所有元素
Stream().distinct()方法返回一個保證元素唯一的新流,如果想要檢查去重後的流中是否包含某個元素,可以使用forEach()方法遍歷整個流,並輸出所有遍歷到的元素。
下面是一個例子:
List numbers = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 5, 6); List distinctNumbers = numbers.stream().distinct().collect(Collectors.toList()); distinctNumbers.forEach(System.out::println);
輸出結果:
1 2 3 4 5 6
七、小結
在Java 8中,Stream介面支持函數式編程風格,提供了distinct()方法用於對流中元素進行去重。使用distinct()方法需要注意重寫equals()和hashCode()方法,可以用於從數據集中獲得唯一元素的場景。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/246895.html