如何使用流外部的值使用Java流API创建映射?
我想初始化一个Map
并希望始终从流外部添加相同的BigDecimal
值。
BigDecimal samePrice; Set set; set.stream().collect(Collectors.toMap(Function.identity(), samePrice));
但是Java抱怨如下:
收集器类型中的Map(Function,Function)方法不适用于参数(Function,BigDecimal)
为什么我不能从外面使用BigDecimal? 如果我写:
set.stream().collect(Collectors.toMap(Function.identity(), new BigDecimal()));
它会起作用,但那当然不是我想要的。
toMap(keyMapper, valueMapper)
的第二个参数(如第一个参数toMap(keyMapper, valueMapper)
是一个获取stream元素并返回map值的函数。
在这种情况下,您要忽略它,以便您可以:
set.stream().collect(Collectors.toMap(Function.identity(), e -> samePrice));
请注意,您的第二次尝试不会出于同样的原因。
Collectors#toMap
需要两个Functions
set.stream().collect(Collectors.toMap(Function.identity(), x -> samePrice));
您可以在JavaDoc中找到几乎相同的示例
Map
studentToGPA students.stream().collect(toMap(Functions.identity(), student -> computeGPA(student)));
正如在其他答案中已经说过的那样,你需要指定一个函数,它将每个元素映射到固定值,如element -> samePrice
。
另外,如果你想专门填充ConcurrentHashMap
,有一个简洁的function,根本不需要流操作:
ConcurrentHashMap map = new ConcurrentHashMap<>(); map.keySet(samePrice).addAll(set);
不幸的是,任意Map
都没有这样的操作。