dinhokz
dinhokz

Reputation: 977

How to convert the values of a Map of List to a single List

How is the best (efficient and simple) way to convert the values of a Map<Object1, List<Object2>> to a List<Object2>. Should I simply iterate over all entries and adAll the items to a list?

Upvotes: 9

Views: 12707

Answers (3)

dinhokz
dinhokz

Reputation: 977

Just found it:

 List<Object2> list = myMap.values()
                           .stream()
                           .flatMap(item -> item.stream())
                           .collect(Collectors.toList()));

Upvotes: 0

Nick Ziebert
Nick Ziebert

Reputation: 1268

Here's a third way so you don't need to create an ArrayList, which is what you actually asked. This is the proper way to use streams because you're not changing the state of any object.

List<Object2> values = myMap.values()
                            .stream()
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());

Upvotes: 21

Jon
Jon

Reputation: 5357

One option using addAll.

List<Object2> list = new ArrayList<>();
myMap.values().forEach(list::addAll);

Upvotes: 0

Related Questions