一、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/n/136433.html
微信扫一扫
支付宝扫一扫