一、Distinct方法簡介
/**
* 返回能夠保證流中無重複元素的流,根據元素的natural ordering比較。
* 等價於:
* return distinct(comparing(Object::toString));
*
* 如果要根據比較器進行去重,則應使用sorted(Comparator)來指定比較器。
*
* @return 返回一個無重複元素的流。
*/
@Override
public Stream distinct() {
return distinct(Object::equals);
}
java 8中的Distinct方法是一種能夠保證流中無重複元素的方法。它默認使用元素的自然排序比較來實現這一功能,使用起來相對簡單,而且十分高效。
二、Distinct方法構造
Distinct方法有多種構造方式,供用戶根據不同的場景選擇。
1.默認構造器
Stream distinct();
默認構造器的作用是返回一個無重複元素的流。Distinct方法默認根據元素的自然排序比較來去重。
2.自定義比較器的構造器
Stream distinct(Comparator comparator);
自定義比較器的構造器可以指定比較器來進行去重。它比默認構造器更加靈活,可以根據用戶特定的要求進行去重。
3.根據元素屬性去重的構造器
static Function mapper;
static Predicate predicate;
<R> Stream distinct(Function keyExtractor);
根據元素屬性去重的構造器可以通過元素的某個屬性來進行去重。比如:
//去重一個字元串流
Stream.of("apple", "orange", "banana", "apple").distinct().forEach(System.out::println);
//結果是:apple, orange, banana
//去重一個對象流
class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Stream.of(new Person("Alice", 18), new Person("Bob", 20), new Person("Alice", 22))
.distinct("name")
.forEach(p -> System.out.println(p.name + ", " + p.age));
//結果是:Alice, 18 Bob, 20
三、Distinct方法的使用場景
Distinct方法通常應用在需要去重的場景。比如:
1.拼接字元串去重
List list = Arrays.asList("a", "b", "c", "b", "c", "d");
String result = list.stream().distinct().collect(Collectors.joining(", "));
System.out.println(result);
//結果是:a, b, c, d
2.對象去重
//按照對象屬性去重一個對象流
class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
List list = Arrays.asList(
new Person("Alice", 18),
new Person("Bob", 20),
new Person("Alice", 22),
new Person("Bob", 25));
List uniqueList = list.stream().distinct().collect(Collectors.toList());
uniqueList.forEach(p -> System.out.println(p.name + ", " + p.age));
//結果是:Alice, 18 Bob, 20 Alice, 22 Bob, 25
//按照對象的某個屬性去重一個對象流
List uniqueList2 = list.stream()
.distinct(p -> p.name)
.collect(Collectors.toList());
uniqueList2.forEach(p -> System.out.println(p.name + ", " + p.age));
//結果是:Alice, 18 Bob, 20
3.去除重複元素
int[] arr = {1, 2, 3, 2, 3, 4, 5, 6, 5};
Arrays.stream(arr).distinct().forEach(System.out::println);
//結果是:1, 2, 3, 4, 5, 6
四、Distinct方法的性能分析
Distinct方法在處理大數據量時比起普通的去重演算法佔有很大的優勢。在性能優化時,建議使用Distinct方法來進行數據去重。
五、總結
Java 8中的Distinct方法是一種十分高效的去重方法,它默認使用元素的自然排序比較來實現去重功能。同時,Distinct方法還支持多種構造方式,以滿足用戶的不同需求。在處理大數據量時,Distinct方法比起普通的去重演算法佔有很大的優勢。
原創文章,作者:YCYN,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/136433.html
微信掃一掃
支付寶掃一掃