简体   繁体   English

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

[英]How to insert the same value for multiple keys of an HashMap using Java Streams

Say I have a HashMap and I want to insert the same value to a list of keys. 假设我有一个HashMap,我想将相同的值插入到一个键列表中。 How can I do this with Java 8 without iterating through all the keys and inserting the value? 如何在不迭代所有键并插入值的情况下使用Java 8执行此操作? This is more of a Java Streams question. 这更像是一个Java Streams问题。

Here is the straight forward way of doing it. 这是直截了当的做法。 This is a sample code that I wrote to demonstrate what I wanted to achieve. 这是我编写的示例代码,用于演示我想要实现的目标。

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

Is there a simpler way of doing the above using Java 8 streams? 有没有更简单的方法使用Java 8流进行上述操作? How can I avoid the for loop using Java 8 streams. 如何避免使用Java 8流的for循环。 Thanks! 谢谢!

[Edit-1] A better code snippet below. [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);
    } 
}

Using collector, something like: 使用收集器,如:

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

I think that your question is about factoring out some piece of code more than converting traditional for loops into stream constructs. 我认为你的问题是将一些代码分解出来而不是将传统的for循环转换为流构造。

Suppose you have the following generic utility method: 假设您具有以下通用实用程序方法:

public static <K, V, M extends Map<K, V>> M fillMap(
        Supplier<List<K>> keysFactory,
        Supplier<V> singleValueFactory,
        Supplier<M> mapFactory) {

    M map = mapFactory.get();
    List<K> keys = keysFactory.get();
    V singleValue = singleValueFactory.get();

    keys.forEach(k -> map.put(k, singleValue));

    return map;
}

Then, you could use the above method as follows: 然后,您可以使用以下方法:

Map<String, Integer> myMap = fillMap(() -> getKeysFromAnotherFunction(),
                                     () -> getValueToBeInserted(),
                                     HashMap::new); // create HashMap

myMap = fillMap(() -> getNextSetOfKeys(),
                () -> getValueToBeInserted(),
                () -> myMap); // use previously created map

There are variants for the code above, ie, the method could receive a Map<K, V> instance instead of a Supplier<Map<K, V>> , or it might even be overloaded to support both variants. 上面的代码有变种,即该方法可以接收Map<K, V>实例而不是Supplier<Map<K, V>> ,或者甚至可能超载以支持两种变体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将多个键链接到 HashMap 中的相同值 - How link multiple keys to the same value in the HashMap 如何将具有相同值的多个键插入到 Java 中的哈希映射中? - How to insert multiple keys with the same value into a hash map in Java? 在Java中使用Hashmap是否可以打印出数量相同的键? - Using a Hashmap in Java is it possible to print out the amount of keys will a same value? 如何使用mybatis在数据库中插入java HashMap键和值作为列 - How to insert java HashMap keys and values as columns in database using mybatis 如何在Java中的Same HashMap中查看多个键之间的公共值? - How to view the common Values between multiple keys in Same HashMap in java? Java:如何在hashmap中获取具有相同值的键集 - Java: How to get set of keys having same value in hashmap Java 8: how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams? - Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams? 如何使用 Java 8 流获取每个不同键的第一个值? - How to get the first value for each distinct keys using Java 8 streams? Hashmap with Streams in Java 8 Streams 收集值 Map - Hashmap with Streams in Java 8 Streams to collect value of Map 一个具有多个价值键的哈希图? - a hashmap with multiple keys to value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM