我想初始化一个 Map<String, BigDecimal>
并希望始终将相同的 BigDecimal
来自流外部的值。
BigDecimal samePrice;
Set<String> set;
set.stream().collect(Collectors.toMap(Function.identity(), samePrice));
然而 Java 提示如下:
The method toMap(Function, Function) in the type Collectors is not applicable for the arguments (Function, BigDecimal)
为什么我不能从外部使用 BigDecimal?如果我写:
set.stream().collect(Collectors.toMap(Function.identity(), new BigDecimal()));
它会起作用,但这当然不是我想要的。
最佳答案
toMap(keyMapper, valueMapper)
的第二个参数(和第一个参数一样)是一个接受流元素并返回 map 值的函数。
在这种情况下,你想忽略它,这样你就可以拥有:
set.stream().collect(Collectors.toMap(Function.identity(), e -> samePrice));
请注意,出于同样的原因,您的第二次尝试不会奏效。
关于java - 如何使用流外的值创建带有 Java 流 API 的 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36356041/