Foenix
Foenix

Reputation: 558

Collect values from HashMap into one array using streams api

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.

Upvotes: 0

Views: 534

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59970

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));

Upvotes: 4

Related Questions