单个属性去重
/**
* 3-1. 对单个属性一样的数据进行去重,下面是对`mobile`去重
*/
public static void oneColumnDistinctMethodOne() {
List<SyncBalance> oneColumnDistinctMethodOne = list.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(SyncBalance::getMobile))), ArrayList::new));
}
/**
* 3-2. 对单个属性一样的数据进行去重,下面是对`mobile`去重(通过自定义属性去重方法)
*/
public static void oneColumnDistinctMethodTwo() {
List<SyncBalance> oneColumnDistinctMethodTwo = list.stream().filter(distinctByKey(i -> i.getMobile())).collect(Collectors.toList());
}
/**
* list对象单个个字段去重(自定义属性)
* @param keyExtractor 去重的对象字段
* @return
* @param <T>
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
/**
* 3-3. 对单个属性一样的数据进行去重,下面是对`mobile`去重
* 利用TreeSet进行去重
*/
public static void oneColumnDistinctMethodThree() {
TreeSet<SyncBalance> oneColumnDistinctMethodThree = new TreeSet<>(Comparator.comparing(i -> i.getMobile()));
list.forEach(a -> oneColumnDistinctMethodThree.add(a));
}
多个属性去重
/**
* 4. 多个字段条件去重
*/
public static void twoColumnDistinct() {
List<SyncBalance> twoColumnDistinct = list.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(p -> p.getMobile() + ";" + p.getStatus()))), ArrayList::new));
}
验证方法
对于验证方法添加了一些分隔的数据
/**
* 验证的main方法
* @param args
*/
public static void main(String[] args) {
allColumnDistinct();
columnDistinct();
oneColumnDistinctMethodOne();
oneColumnDistinctMethodTwo();
oneColumnDistinctMethodThree();
twoColumnDistinct();
}
原文链接:https://blog.csdn.net/CSDN_JAVA_CC/article/details/146564325