[英]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.