从流分组中获取唯一日期列表

get a list of unique date from the stream grouping

我有数据:

id|date
1 |12-12-2021
2 |12-12-2021
3 |13-12-2021

想要获取日期列表:["12-12-2021", "13-12-2021"]

使用流,我可以得到一张地图:

txs.stream().collect(Collectors.groupingBy(g -> g.getDate()));

我想从上面的流中转换为列表。

如果您有 Map<Integer,LocalDate> 中的数据,您可以使用 values() 并收集到 Set 以消除重复项

Set<LocalDate> dates = txs.values().stream().collect(Collectors.toSet())

或使用HashSet

new HashSet<>(txs.values());

groupingBy 不是您的最佳选择。请改用 distinct。它会自动过滤掉所有重复项。

txs.stream().map(g -> g.getDate()).distinct().collect(Collectors.toList());