我想知道如何提取 List<D>
来自HashMap<E,R>
考虑到这些限制:
-
E
是自定义类; -
R
是包含Set<D>
的自定义类自定义对象;
我尝试过的:我尝试解决 this question 中的问题.
在之前的案例中,我有一个简单的 Map<E,List<R>>
,但在这种情况下,我必须访问 R
具有目标 Set<D>
的类.
我想在接下来的代码部分中获取 Set<D>
的元素。其国家名称等于给定参数。
我试过使用相同的解决方案:
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)
:
return map.values()
.stream()
.filter(x -> x.getSet().stream().anyMatch(t -> t.getCountry().equals(countryname)))
.map(R::getSet)
.flatMap(Set::stream)
.collect(Collectors.toList());
此外,正如您在上面注意到的那样,如果您在不必要时避免使用花括号,代码的可读性会更高。
关于java - 如何使用流从 HashMap<E,R> 中提取 List<D>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070685/