这是我尝试过的代码:
Map<LocalDate, List<Records>> outputs = new HashMap<>();
Map<String, List<Records>> prevDateData = outputs.get(currentDate.minusDays(1))
.stream().collect(Collectors.groupingBy(Records::getId));但我想从输出中实现数据结构:
Map<String, Records> prevDateData有人能建议我怎么做吗?
发布于 2022-11-02 09:08:09
您可以保留列表中的所有Records,需要应用一些用于应用映射到相同键的逻辑解析Records的逻辑。例如,保留具有最新时间戳的那个,否则就不可能了。
这就是如何使用三args风格的收集器toMap()来完成的。
Map<String, List<Records>> prevDateData = outputs.get(currentDate.minusDays(1))
.stream()
.collect(Collectors.toMap(
Records::getId, // keyMapper
Function.identity(), // valueMapper
(left, right) -> *your logic for resolving duplicates here* // mergeFunction
));最简单的示例mergeFunction是(l, r) -> r,它用一个新的值覆盖以前关联的值。你可能想要更精细的东西。
合并函数的类型为BinaryOperator,基于提供的比较器生成BinaryOperator的静态方法minBy()和maxBy()可能有助于实现合并函数。
https://stackoverflow.com/questions/74286612
复制相似问题