汇总列表< String>放入HashMap< String,T>使用流API [英] Aggregate List<String> into HashMap<String, T> using Stream API
问题描述
我有一个MultivaluedMap
和一个字符串列表,我想看看那些字符串中的哪个是MultivaluedMap
中的键.对于MultivaluedMap
中作为键的每个字符串,我想根据该键的值构造一个新的Thing
,将该字符串设置为新的HashMap<String, Thing>
中的新键,然后设置新的Thing
我已经在HashMap
中为该新键创建了值.
I have a MultivaluedMap
and a list of strings, and I would like to see which of those string are keys in the MultivaluedMap
. For each of the strings that are keys in the MultivaluedMap
, I want to construct a new Thing
out of the value of that key, set that string as a new key in a new HashMap<String, Thing>
, and set the new Thing
I've created as the value for that new key in the HashMap
.
现在,使用香草forEach
,我有以下可行的解决方案:
Right now, using a vanilla forEach
, I have the following working solution:
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
HashMap<String, Thing> result = new HashMap<String, Thing>();
listOfStrings.forEach( (key) -> {
String value = params.getFirst(key);
if (value != null && !value.isEmpty()) {
result.put(key, new Thing(value));
}
});
但是,我想使用Java Stream API为此实现一个功能解决方案,并尝试了一些解决方案.我有以下内容,看起来应该可以,但不能:
However, I would like to implement a functional solution to this using the Java Stream API, and have attempted a fews solution. I have the following, which looks like it should work, but it does not:
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
HashMap<String, Thing> result = listOfStrings
.stream()
.filter(params::containsKey)
.map( e -> new AbstractMap.SimpleEntry<String, Thing>(e, new Thing(params.getFirst(e))))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
Entry::getKey
和Entry::getValue
给出了"不能从静态上下文引用非静态方法".我尝试了其他变体:在keyMapper
和valueMapper
lambda中构造对象,并使用带有空映射的reduce作为初始值.没有一个起作用.
The Entry::getKey
and Entry::getValue
are giving a "Non-static method cannot be referred from a static context". I've tried other variations of this: constructing the objects in keyMapper
and valueMapper
lambdas, and using reduce with an empty map as the initial value. None have worked.
如何使用Java Stream API和聚合(例如collect
,reduce
)重写我的第一个可行的解决方案?我已引用此帖子和此帖子.
How would I rewrite my first, working solution using the Java Stream API and aggregation (e.g. collect
, reduce
)? I have referenced this post and this post and this post.
推荐答案
您的代码很好.您只需要将返回类型更改为Map
而不是HashMap
.如果需要专门将其设置为HashMap
,则可以将HashMap::new
传递到
Your code is fine. You just need to change the return type to Map
instead of HashMap
. If you need it to be HashMap
specifically, you can pass HashMap::new
into the factory overload.
我要做的一项改进是删除不必要的map()
操作并在收集器中进行查找:
One improvement I'd make is to cut out the unnecessary map()
operation and do the lookup in the collector:
Map<String, Thing> result = listOfStrings
.stream()
.filter(params::containsKey)
.collect(Collectors.toMap(Function.identity(), k -> new Thing(params.getFirst(k))));
这篇关于汇总列表< String>放入HashMap< String,T>使用流API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!