如何提取List< D>来自HashMap< E,R>使用流 [英] How to extract a List<D> from a HashMap<E,R> using stream
问题描述
考虑到这些限制,我想知道如何从HashMap<E,R>
中提取List<D>
:
I want to know how to extract a List<D>
from a HashMap<E,R>
considering these constraints:
-
E
是一个自定义类; -
R
是一个包含Set<D>
自定义对象的自定义类;
E
is a custom class;R
is a custom class containing aSet<D>
of custom objects;
我尝试过的方法:我尝试在中解决此问题这个问题.
What I have tried: I tried addressing the issue in this question.
在以前的情况下,我有一个简单的Map<E,List<R>>
,但是在这种情况下,我必须访问具有目标Set<D>
的R
类.
In that previous case, I had a simple Map<E,List<R>>
, but in this case I have to access the R
class which has the targeted Set<D>
.
在代码的以下部分中,我要做的是获取国家名称等于给定参数的Set<D>
的元素.
What I want to do in the following portion of the code is to get the Elements of the Set<D>
whose country names are equal to the given parameter.
我尝试使用相同的解决方案:
I have tried using the same solution :
Map<E,R> map = new HashMap<E,R>();
public List<D> method(String countryname) {
return map.values().stream().filter((x)->{
return x.getSet().stream().anyMatch((t) -> {
return t.getCountry().equals(countryname);
});
})
.map(R::getSet)
.flatMap(List::stream)
.collect(Collectors.toList()); //does not compile
}
// the R class
class R {
private Set<D> set = new TreeSet<D>();
//getters & setters & other attributes
}
推荐答案
我相信flatMap
步骤是错误的,因为您的map
步骤将您的Stream<R>
转换为Stream<Set<D>>
,因此flatMap(List::stream)
应该是flatMap(Set::stream)
:
I believe the flatMap
step is wrong, since your map
step transforms your Stream<R>
to a Stream<Set<D>>
, so flatMap(List::stream)
should be flatMap(Set::stream)
:
return map.values()
.stream()
.filter(x -> x.getSet().stream().anyMatch(t -> t.getCountry().equals(countryname)))
.map(R::getSet)
.flatMap(Set::stream)
.collect(Collectors.toList());
此外,正如您在上面注意到的那样,如果不必使用花括号,则代码可以更具可读性.
Besides, as you can notice above, the code can be much more readable if you avoid using curly braces when you don't have to.
这篇关于如何提取List< D>来自HashMap< E,R>使用流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!