问题描述
有一个List,里面的元素有多个属性,我们需要根据里面的2个(或者多个)属性来对这个List去重。
实现方法
代码如下:
public static void main(String[] args) {
List<SomeObject> list = new ArrayList<>();
list.add(new SomeObject("abc", 100));
list.add(new SomeObject("abc", 100));
list.add(new SomeObject("def", 100));
list.add(new SomeObject("def", 200));
List<SomeObject> distinctedList = list.stream()
// 把需要作为唯一值判断的条件的多个属性,组装成一个string,用这个string作为唯一值判断
.filter(distinctByKey(p -> p.getName() + "_" + p.getPrice()))
.collect(Collectors.toList()));
}
class SomeObject() {
private final String name;
private final Integer price;
public SomeObject(String name, Integer price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public Integer getPrice() {
return price;
}
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
实现了一个distinctByKey返回一个Predicate,传入需要作为唯一值判断依据,使用list stream的filter来筛选。
文章评论