Confused by Java8 Collectors.toMap(被 Java8 Collectors.toMap 弄糊涂了)
问题描述
我有一个如下所示的集合,我想过滤掉除非月末日期之外的所有内容.
I have a collection that looks like below, and I want to filter out the everything except the dates that aren't the end of the months.
2010-01-01=2100.00,
2010-01-31=2108.74,
2010-02-01=2208.74,
2010-02-28=2217.92,
2010-03-01=2317.92,
2010-03-31=2327.57,
2010-04-01=2427.57,
2010-04-30=2437.67,
2010-05-01=2537.67,
2010-05-31=2548.22,
2010-06-01=2648.22,
2010-06-30=2659.24,
2010-07-01=2759.24,
2010-07-31=2770.72,
2010-08-01=2870.72,
2010-08-31=2882.66,
2010-09-01=2982.66,
2010-09-30=2995.07,
2010-10-01=3095.07,
2010-10-31=3107.94,
2010-11-01=3207.94,
2010-11-30=3221.29
我有以下过滤条件.frequency.getEnd
返回与给定 LocalDate
的月末匹配的 LocalDate
.
I have the following filter criteria. frequency.getEnd
returns a LocalDate
matching the end of the month for the given LocalDate
.
.filter(p -> frequency.getEnd(p.getKey()) == p.getKey())
所以现在我想我必须将这个过滤后的流转换回地图.我想我使用收集器来做到这一点.因此我补充说:
So now I think I have to converted this filtered stream back to a map. And I think I use a collector to do that. Thus I add:
.collect(Collectors.toMap(/* HUH? */));
但我不知道如何处理 Collectors.toMap
.阅读示例让我感到困惑.这是我当前的代码,显然不起作用.
But I don't know what to do with Collectors.toMap
. Reading examples leaves me confused. Here's my current code which obviously doesn't work.
TreeMap<LocalDate, BigDecimal> values = values.entrySet()
.stream()
.filter(p -> frequency.getEnd(p.getKey()) == p.getKey())
.collect(Collectors.toMap(/* HUH? */));
推荐答案
除了前面的答案注意,如果你不需要保留原始地图,你可以在不使用 Stream API 的情况下就地执行这样的过滤:
In addition to the previous answers note that if you don't need to keep the original map, you can perform such filtering in-place without using the Stream API:
values.keySet().removeIf(k -> !frequency.getEnd(k).equals(k));
这篇关于被 Java8 Collectors.toMap 弄糊涂了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:被 Java8 Collectors.toMap 弄糊涂了


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01