How to extract a List<R> from a HashMap<E,R> using stream

  • A+

I want to know how to extract a List<D> from a HashMap<E,R> considering these constraints:

  • E is a custom class;
  • R is a custom class containing a Set<D> of custom objects;

What I have tried: I tried addressing the issue in this question.

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>.

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 } 


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: