【发布时间】:2017-05-05 22:21:34
【问题描述】:
我有一个流,我想明确地将它收集到一个 HashMap 中。现在,我正在做类似的事情
List<Item> listToTransform = //initialized and populated
HashMap<K, V> myHashMap = new HashMap<>();
listToTransform.stream().map(/* do my transformation here */)
.forEach(i -> myHashMap.put(i.getKey(), i.getValue()));
我想知道是否有一种方法可以使用 Collectors 显式取回 HashMap。
【问题讨论】:
-
您可以将
Collectors.toMap与供应商功能一起使用。
标签: java java-8 hashmap java-stream