说我有一个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);
}
}
是否有使用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);
}
}
答案 0 :(得分:3)
使用收集器,例如:
Map<String, Integer> myMap = keys.stream()
.collect(Collectors.toMap(key -> key,
val -> value, (a, b) -> b));
答案 1 :(得分:0)
我认为您的问题是要分解出一些代码,而不是将传统的string url = "www.test~dummy.com";
foreach (string x in url.Split('~'))
{
element.SendKeys(x);
element.SendKeys("\u223C");
}
element.SendKeys(Keys.Backspace); //this is used to erase the wrong tilde typed at the end of the URL
循环转换为流结构。
假设您具有以下通用实用程序方法:
for
然后,您可以按以下方式使用上述方法:
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;
}
上面的代码有多种变体,即该方法可以接收Map<String, Integer> myMap = fillMap(() -> getKeysFromAnotherFunction(),
() -> getValueToBeInserted(),
HashMap::new); // create HashMap
myMap = fillMap(() -> getNextSetOfKeys(),
() -> getValueToBeInserted(),
() -> myMap); // use previously created map
实例而不是Map<K, V>
,或者甚至可以重载以支持这两种变体。