如何使用 Java Streams 为 HashMap 的多个键插入相同的值

Syn*_*ter 3 java hashmap java-8 java-stream

假设我有一个 HashMap,我想将相同的值插入到键列表中。如何使用 Java 8 执行此操作,而无需迭代所有键并插入值?这更多的是一个 Java Streams 问题。

这是执行此操作的直接方法。这是我编写的示例代码,用于演示我想要实现的目标。

public void foo(List<String> keys, Integer value) {
    Map<String, Integer> myMap = new HashMap<>(); 
    for (String key : keys) {
        myMap.put(key, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法使用 Java 8 流来执行上述操作?如何使用 Java 8 流避免 for 循环。谢谢!

[Edit-1] 下面是更好的代码片段。

public void foo() {
    Map<String, Integer> myMap = new HashMap<>(); 
    List<String> keys = getKeysFromAnotherFunction();
    Integer value = getValueToBeInserted(); // Difficult to show my actual use case. Imagine that some value is getting computed which has to be inserted for the keys.
    for (String key : keys) {
        myMap.put(key, value);
    }  

    List<String> keys2 = getNextSetOfKeys();
    Integer newValue = getValueToBeInserted(); 
    for (String key : keys2) {
        myMap.put(key, newValue);
    } 
}
Run Code Online (Sandbox Code Playgroud)

Nam*_*man 6

使用收集器,例如:

Map<String, Integer> myMap = keys.stream()
            .collect(Collectors.toMap(key -> key,
                    val -> value, (a, b) -> b));
Run Code Online (Sandbox Code Playgroud)