How to create a map with Java stream API using a value outside the stream?(如何使用流外的值创建带有 Java 流 API 的地图?)
问题描述
我想初始化一个 Map<String, BigDecimal> 并希望始终从流外部放置相同的 BigDecimal 值.
I want to init a Map<String, BigDecimal> and want to always put the same BigDecimal value from outside of the stream.
BigDecimal samePrice;
Set<String> set;
set.stream().collect(Collectors.toMap(Function.identity(), samePrice));
然而 Java 抱怨如下:
However Java complains as follows:
类型 Collectors 中的方法 toMap(Function, Function) 不适用于参数(函数,BigDecimal)
The method toMap(Function, Function) in the type Collectors is not applicable for the arguments (Function, BigDecimal)
为什么我不能从外部使用 BigDecimal?如果我写:
Why can't I use the BigDecimal from outside? If I write:
set.stream().collect(Collectors.toMap(Function.identity(), new BigDecimal()));
它会起作用,但这当然不是我想要的.
it would work, but that's of course not what I want.
推荐答案
toMap(keyMapper, valueMapper) 是一个函数,它接受流元素并返回映射的值.
The second argument (like the first one) of toMap(keyMapper, valueMapper) is a function that takes the stream element and returns the value of the map.
在这种情况下,你想忽略它,这样你就可以拥有:
In this case, you want to ignore it so you can have:
set.stream().collect(Collectors.toMap(Function.identity(), e -> samePrice));
请注意,出于同样的原因,您的第二次尝试不会奏效.
Note that your second attempt wouldn't work for the same reason.
这篇关于如何使用流外的值创建带有 Java 流 API 的地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用流外的值创建带有 Java 流 API 的地图?
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
