Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map values to ArrayList

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?

like image 764
Hugo Silva Avatar asked Mar 16 '16 18:03

Hugo Silva


People also ask

Can we convert map to list?

We can convert Map keys to a List of Values by passing a collection of map values generated by map. values() method to ArrayList constructor parameter.

Can the value of a HashMap be an ArrayList?

As HashMap contains key-value pairs, there are three ways you can convert given HashMap to ArrayList. You can convert HashMap keys into ArrayList or you can convert HashMap values into ArrayList or you can convert key-value pairs into ArrayList.

Is map faster than ArrayList?

The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.


2 Answers

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.

like image 68
Paul Boddington Avatar answered Sep 23 '22 03:09

Paul Boddington


You could iterate over the values of the Map:

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

for (MyClass e : map.values()) {
    list.add(e.objj);
}
like image 41
Marv Avatar answered Sep 23 '22 03:09

Marv