一、根据对象中某个属性去重
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));