如何使用流从HashMap <E,R>中提取List <D>

Yas*_*ida 8 java collections hashmap java-8 java-stream

我想知道如何List<D>HashMap<E,R>考虑这些约束中提取a :

  • E 是一个自定义类;
  • R是包含Set<D>自定义对象的自定义类;

我尝试过:我试着在这个问题上解决这个问题.

在之前的情况下,我有一个简单的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
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

我相信这flatMap一步是错误的,因为你的map步骤将你的转化Stream<R>为 a 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());
Run Code Online (Sandbox Code Playgroud)

此外,正如您在上面注意到的,如果您在不必要时避免使用花括号,则代码的可读性会更高。

  • @nullpointer 假设 `getSet()` 始终返回相同或等效的集合,OP 的代码和此解决方案将包含所有集合的 *all* 元素,其中至少包含一个匹配元素,而您的解决方案将仅包含匹配元素。 (3认同)