8

I have a Map<Integer, MyClass> and MyClass has 2 fields, Object1 obj and Object2 objj for example.

How can I create an ArrayList<Object2> with all Object2 values?

Must I iterate the Map and then add the values to the ArrayList or exists another way?

Marv
  • 3,517
  • 2
  • 22
  • 47
Hugo Silva
  • 517
  • 1
  • 6
  • 11

3 Answers3

15

If you are using Java 8 you could do:

List<Object2> list = map.values()
                        .stream()
                        .map(v -> v.objj)
                        .collect(Collectors.toList());

If you are using Java 7 or earlier, the solution of @Marv is the simplest.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
10

You could iterate over the values of the Map:

ArrayList<Object2> list = new ArrayList<>();

for (MyClass e : map.values()) {
    list.add(e.objj);
}
Marv
  • 3,517
  • 2
  • 22
  • 47
5

Checkout following :

How to convert a Map to List in Java?

It has one liner snippet for your question.

List<Object2> list = new ArrayList<Object2>(map.values());

assuming:

Map<Integer, MyClass> map;
Community
  • 1
  • 1
Chirag Parmar
  • 833
  • 11
  • 26