0

I have a map, containing strings as a key and ArrayList as values. I want to use stream api to get as a result all the Arrays from values as one array.

Map<Integer,  ArrayList<String>> map = new HashMap<>();

Result: one ArrayList<String> containing all the Strings from value arrays and preferably unique values.

YCF_L
  • 49,027
  • 13
  • 75
  • 115
MyFoenix
  • 300
  • 3
  • 11
  • What did you try so far? What didn't work? – Amongalen Oct 14 '20 at 10:26
  • of course I googled, I just did not find rights words) thanks for the link. I tried flatmap first, but I did not know that it should be List::stream inside. – MyFoenix Oct 14 '20 at 10:28
  • 1
    @MyFoenix in any case, it can be done with method reference, or `.flatMap(a -> a.stream())` but the method reference in this case is better – YCF_L Oct 14 '20 at 10:32

1 Answers1

3

Are you looking to this :

List<String> distinctValues = map.values().stream() // Stream<ArrayList<String>>
        .flatMap(List::stream)                      // Stream<String>
        .distinct()
        .collect(Collectors.toList());

If you prefer ArrayList as a result, then use :

        .collect(Collectors.toCollection(ArrayList::new));
YCF_L
  • 49,027
  • 13
  • 75
  • 115