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.

3
  • What did you try so far? What didn't work? Commented Oct 14, 2020 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. Commented Oct 14, 2020 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 Commented Oct 14, 2020 at 10:32

1 Answer 1

4

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.