java 8 利用stream针对List集合根据对象属性去重

一、根据对象中某个属性去重
1、创建提取方法
private  Predicate distinctByKey(Function keyExtractor) {
    Map concurrentHashMap = new ConcurrentHashMap<>();
    return t -> concurrentHashMap.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
2、利用filter
List codeDistinctList = testCommodityList
            .stream()
            .filter(distinctByKey(TestCommodity::getCode))
            .collect(Collectors.toList());
二、根据对象中多个个属性去重,利用collectingAndThen
List cbList = testCommodityList
            .stream()
            .collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(
                            () -> new TreeSet<>(
                                    Comparator.comparing(
                                            tc -> tc.getCode() + ";" + tc.getBarCode()))), ArrayList::new));
三、分组后取价格最高的对象
Map maxPriceCommodityMap = testCommodityList
            .stream()
            .collect(
                    Collectors.groupingBy(
                            TestCommodity::getCode,
                            Collectors.collectingAndThen(
                                    Collectors.maxBy(
                                            Comparator.comparingDouble(TestCommodity::getPrice)),Optional::get)));
四、附java8 map 遍历方法
maxPriceCommodityMap.forEach((k, v) -> System.out.println(k + ":" + v));

你可能感兴趣的:(java 8 利用stream针对List集合根据对象属性去重)