如何通过stream流快速处理相同数据下,只想要最新的那条数据
filter过滤无往不利 🥰
List<IndexStockBlockDTO> list = IndexStockBlockList.parallelStream()
//先排序最新的
.sorted(Comparator.comparing(IndexStockBlockDTO::getSource).reversed())
//此处会根据Scode 获取到第一个出现的,过滤其他的
.filter(distinctByKey(IndexStockBlockDTO::getScode))
.collect(Collectors.toList());
//根据最新数据排序后获取相同数据下最新的一个
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
希望对你有所帮助…期待 三连 😊