Liststream对象属性去重单值去重不写了,记录对象去重
随⼿⼀个对象:
@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.Comparatorparing;
import static java.util.ComparatorparingLong;
import static java.util.llectingAndThen;
import static java.util.Collection;
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-&Key()))),ArrayList::new)
);
for (Milk m:uniqueMilk) {
System.out.String());
}
}
}
操作底层是set,视图,⼀堆东西,还是有点意思的,不记录了,有兴趣可深⼊
任何Object类型去重...~
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;java stream
import java.util.Map;
import urrent.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().upingBy(e -> e.get("orderno"))); List<Map<String, Object>> collect = list.stream().filter(distinctByKey(n -> n.get("orderno")))
.List());
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;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论