学会Java8 Stream与TreeSet高效List去重!本文详解对象整体去重、单属性及多属性去重实战代码,直接复制即可用,点击立即掌握集合去重技巧,提升开发效率
目录
- 前言
- 正文
- 数据对象
- 1. 对象整体去重
- 2. 单个属性去重(只返回属性)
- 3. 单个属性去重
- 4. 多个属性去重
- 验证方法
- 运行结果
- 结尾
前言
对于list集合进行去重操作,多种情况进行记录.
只记录在学习与实践过程中需要对集合操作的场景,方便下次能够直接快速的回忆起来.
当然这些方法的使用与操作皆是对于Java8的stream操作,TreeSet不重复特性进行的运用.
如果能够更好更快的达成目的,也是不必拘泥于某一些固定的方式去处理数据,以效率与程序开销优先.
正文
数据对象
将数据对象写成静态不可变的list来方便我们对于程序进行调用验证
private static final List list = asList(
new SyncBalance(BigDecimal.ZERO, "12345678", 0, 1, "GGBond", 32, 0),
new SyncBalance(BigDecimal.ZERO, "22345678", 0, 1, "GGBond", 32, 0),
new SyncBalance(BigDecimal.ZERO, "22345678", 1, 1, "GGBond", 32, 0),
new SyncBalance(BigDecimal.ZERO, "22345678", 1, 1, "GGBond", 32, 0)
);
1. 对象整体去重
/**
* 1. 对所有属性一样的数据进行去重
*/
public static void allColumnDistinct() {
List allColumnDistinct = list.stream().distinct().collect(Collectors.toList());
}
2. 单个属性去重(只返回属性)
/**
* 2. 对单个属性去重,只返回去重的属性
*/
public static void columnDistinct() {
List columnDistinct = list.stream().map(SyncBalance::getMobile).distinct().collect(Collectors.toList());
}
3. 单个属性去重
/**
* 3-1. 对单个属性一样的数据进行去重,下面是对`mobile`去重
*/
public static void oneColumnDistinctMethodOne() {
List oneColumnDistinctMethodOne = list.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet(
Comparator.comparing(SyncBalance::getMobile))), ArrayList::new));
}
/**
* 3-2. 对单个属性一样的数据进行去重,下面是对`mobile`去重(通过自定义属性去重方法)
*/
public static void oneColumnDistinctMethodTwo() {
List oneColumnDistinctMethodTwo = list.stream().filter(distinctByKey(i -> i.getMobile())).collect(Collectors.toList());
}
/**
* list对象单个个字段去重(自定义属性)
* @param keyExtractor 去重的对象字段
* @return
* @param
*/
public static Predicate distinctByKey(Function keyExtractor) {
Map