List stream 对象 属性去重

单值去重不写了,记录对象去重

随手一个对象:

@Data
@AllArgsConstructor
public class Milk {
private Integer key;
private String value;
}

操作:

package com.yus.util;

import java.util.*;
import java.util.stream.Collectors; import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection; public class main {
public static void main(String[] args) {
Milk milk0=new Milk(0,"a");
Milk milk1=new Milk(1,"b");
Milk milk2=new Milk(0,"c");
List<Milk> list=new ArrayList<>();
list.add(milk0);
list.add(milk1);
list.add(milk2);
//去重
List<Milk> uniqueMilk = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparing(n->n.getKey()))),ArrayList::new)
); for (Milk m:uniqueMilk) {
System.out.println(m.toString());
} }
}

操作底层是set,视图,collection...一堆东西,还是有点意思的,不记录了,有兴趣可深入

任何Object类型去重...~

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors; public class TestMain { public static void main(String[] args) { List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map = new HashMap<>();
map.put("id", "11");
map.put("orderno", "No.1");
list.add(map); Map<String, Object> map1 = new HashMap<>();
map1.put("id", "2222");
map1.put("orderno", "No.2");
list.add(map1); Map<String, Object> map2 = new HashMap<>();
map2.put("id", "33");
map2.put("orderno", "No.2");
list.add(map2); Map<String, Object> map3 = new HashMap<>();
map3.put("id", "444");
map3.put("orderno", "No.1");
list.add(map3); Map<Object, List<Map<String, Object>>> map0 = list.stream().collect(Collectors.groupingBy(e -> e.get("orderno"))); List<Map<String, Object>> collect = list.stream().filter(distinctByKey(n -> n.get("orderno")))
.collect(Collectors.toList()); collect.forEach(System.out::println);
} private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
上一篇:面试复习(C++)之快速排序


下一篇:php调用短网址接口