美文网首页java
java 8 利用stream针对List集合根据对象属性去重

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

作者: _嘛喳喳_ | 来源:发表于2019-07-26 15:22 被阅读0次
一、根据对象中某个属性去重
1、创建提取方法
private <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
    Map<Object, Boolean> concurrentHashMap = new ConcurrentHashMap<>();
    return t -> concurrentHashMap.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
2、利用filter
List<TestCommodity> codeDistinctList = testCommodityList
            .stream()
            .filter(distinctByKey(TestCommodity::getCode))
            .collect(Collectors.toList());
二、根据对象中多个个属性去重,利用collectingAndThen
List<TestCommodity> cbList = testCommodityList
            .stream()
            .collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(
                            () -> new TreeSet<>(
                                    Comparator.comparing(
                                            tc -> tc.getCode() + ";" + tc.getBarCode()))), ArrayList::new));
三、分组后取价格最高的对象
Map<String, TestCommodity> 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集合根据对象属性去重

    本文链接:https://www.haomeiwen.com/subject/wazrrctx.html