[英]How to create a map with Java stream API using a value outside the stream?
I want to init a Map<String, BigDecimal>
and want to always put the same BigDecimal
value from outside of the stream. 我想初始化一个
Map<String, BigDecimal>
并希望始终从流外部放入相同的BigDecimal
值。
BigDecimal samePrice;
Set<String> set;
set.stream().collect(Collectors.toMap(Function.identity(), samePrice));
However Java complains as follows: 但是Java抱怨如下:
The method toMap(Function, Function) in the type Collectors is not applicable for the arguments (Function, BigDecimal)
收集器类型中的toMap(Function,Function)方法不适用于参数(Function,BigDecimal)
Why can't I use the BigDecimal from outside? 为什么不能从外部使用BigDecimal? If I write:
如果我写:
set.stream().collect(Collectors.toMap(Function.identity(), new BigDecimal()));
it would work, but that's of course not what I want. 它会起作用,但这当然不是我想要的。
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. toMap(keyMapper, valueMapper)
的第二个参数(如第一个参数toMap(keyMapper, valueMapper)
是一个函数,该函数采用stream元素并返回地图的值。
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. 请注意,由于相同的原因,您的第二次尝试将无效。
Collectors#toMap
expects two Functions
Collectors#toMap
需要两个Functions
set.stream().collect(Collectors.toMap(Function.identity(), x -> samePrice));
You can find nearly the same example within the JavaDoc 您可以在JavaDoc中找到几乎相同的示例
Map<Student, Double> studentToGPA students.stream().collect(toMap(Functions.identity(), student -> computeGPA(student)));
As already said in the other answers, you need to specify a function which maps each element to the fixed value like element -> samePrice
. 正如在其他答案中已经说过的那样,您需要指定一个将每个元素映射到固定值的函数,例如
element -> samePrice
。
As an addition, if you want to specifically fill a ConcurrentHashMap
, there is a neat feature that doesn't need a stream operation at all: 另外,如果您要专门填充
ConcurrentHashMap
,则有一个简洁的功能根本不需要流操作:
ConcurrentHashMap<String,BigDecimal> map = new ConcurrentHashMap<>();
map.keySet(samePrice).addAll(set);
Unfortunately, there is no such operation for arbitrary Map
s. 不幸的是,对于任意
Map
都没有这样的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.