我有一个流,我想明确地将它收集到一个 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
方法的重载之一将允许您选择您选择的 map 实现。
不幸的是,这种重载的缺点之一是它还需要一种方法来合并具有相同键的两个值(尽管我经常引用在这种情况下总是抛出异常的方法)。
HashMap<K, V> myHashMap = listToTransform.stream().map(/* do my transformation here */)
.collect(Item::getKey, Item::getValue, this::throwIllegalArgumentException, HashMap::new);
关于java - 如何在 Java 8 中将流转换为 HashMap(而非 Map),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43814537/