1、对于string的去重
直接使用distinct()
public void test() { List<String> strList = new ArrayList<>(); strList.add("A"); strList.add("A"); strList.add("B"); collect = strList.stream().distinct().collect(Collectors.toList()); }
2、对对象的去重
① 使用@Data,重写了equals和hscode,是对所有元素的一个校验去重,直接使用distinct()
@Data public class request { @ApiModelProperty(value = "商品id") @JsonProperty("product_id") private String productId; @ApiModelProperty(value = "商品条码") @JsonProperty("product_bar_code") private String productBarCode; @ApiModelProperty(value = "商品名称") @JsonProperty("product_name") private String productName; }
② 对于指定字段,自定义重写equals和hscode
@Data public class request { @ApiModelProperty(value = "商品id") @JsonProperty("product_id") private String productId; @ApiModelProperty(value = "商品条码") @JsonProperty("product_bar_code") private String productBarCode; @ApiModelProperty(value = "商品名称") @JsonProperty("product_name") private String productName; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; productDetail that = (productDetail) o; return Objects.equals(productId, that.productId) && Objects.equals(productBarCode, that.productBarCode) } @Override public int hashCode() { return Objects.hash(productId, productBarCode); } }
是对商品id和条码的校验去重
③ 引用Collectors两个静态方法collectingAndThen()和toCollection(),以及TreeSet<>来去重
@Test public void test() { List<Person> personList = new ArrayList<>(); personList.add(new Person("zhangsan", 18)); personList.add(new Person("zhangsan", 19)); personList.add(new Person("lisi", 18));
personList = personList.stream().collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new ));
}
④ filter() + 自定义函数
private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }
输入元素的类型是T及其父类,keyExtracctor是映射函数,返回Object,整个传入的函数的功能应该是提取key的。distinctByKey函数返回的是Predicate函数,类型为T
传入一个函数,将传入对象key放入ConcurrentHashMap,数据不重复,返回true,不重复的数据通过filter。
@Test public void test() { List<Person> personList = new ArrayList<>(); personList.add(new Person("zhangsan", 18)); personList.add(new Person("zhangsan", 19)); personList.add(new Person("lisi", 18)); personList = personList.stream().filter(distinctByKey(Person::getName)).collect(Collectors.toList()); }
标签:stream,Person,distinct,流之,private,personList,add,new,public From: https://www.cnblogs.com/shirleyxueli/p/16718070.html