对象去重 ,可自定义实现去重方法,增加特有操作(如:指点字段拼接到一起)
public class Test {
public static class Data extends LambdaUtils<Data>{
private String key;
private String value;
public Data(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
/**
* 去重,指定字段拼接
* @Author hao_hl1314
* @Date 16:28 2019-06-26
* @Param [obj, seen]
* @return boolean
**/
@Override
public boolean customFilter(Data obj, Map<Object, LambdaUtils> seen) {
Data data = (Data) seen.putIfAbsent(obj.getKey(),obj);
if(data == null){
return true;
}
data.setValue(data.getValue() + obj.getValue());
seen.put(data.getKey(),data);
return false;
}
}
public static abstract class LambdaUtils<T>{
/**
* 自定义去重实现
* @Author hao_hl1314
* @Date 16:35 2019-06-26
* @Param [obj, seen]
* @return boolean
**/
public abstract boolean customFilter(T obj,Map<Object,LambdaUtils> seen);
/**
* 自定义去重
* @Author hao_hl1314
* @Date 16:34 2019-06-26
* @Param [extractor]
* @return java.util.function.Predicate<T>
**/
public static <T> Predicate<T> distinctByCustom(Function<? super T,LambdaUtils> extractor) {
Map<Object, LambdaUtils> seen = new ConcurrentHashMap<>();
return t -> extractor.apply(t).customFilter(extractor.apply(t),seen);
}
/**
* 指定Key去重
* @Author hao_hl1314
* @Date 16:34 2019-06-26
* @Param [extractor]
* @return java.util.function.Predicate<T>
**/
public static <T> Predicate<T> distinctByKey(Function<? super T,Object> extractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(extractor.apply(t),Boolean.TRUE) == null;
}
}
@Test
public void testUnique(){
List<Data> datas = new ArrayList<>();
datas.add(new Data("1","1"));
datas.add(new Data("1","2"));
datas.add(new Data("1","3"));
datas.add(new Data("2","4"));
//去重
List<Data> unique = datas.stream().filter(LambdaUtils.distinctByCustom(data -> data)).collect(Collectors.toList());
System.out.println(JSON.toJSONString(unique));
}
}
运行结果