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?
Asked
Active
Viewed 8,952 times
8

Stefan Zobel
- 3,182
- 7
- 28
- 38

dinhokz
- 895
- 15
- 36
3 Answers
20
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());

Nick Ziebert
- 1,258
- 1
- 9
- 17
0
Just found it:
List<Object2> list = myMap.values()
.stream()
.flatMap(item -> item.stream())
.collect(Collectors.toList()));

dinhokz
- 895
- 15
- 36
-
1I misread your requirement, and deleted my answer. I thought you literally wanted a List of Lists. I think the method you gave is probably among the most efficient, barring some clever trick. – Paul Brinkley Mar 30 '17 at 16:53
-
1
-
-
-
0
One option using addAll.
List<Object2> list = new ArrayList<>();
myMap.values().forEach(list::addAll);

Jon
- 5,247
- 6
- 30
- 38
> as myMap.values is a Collection
– dinhokz Mar 30 '17 at 17:35>