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?
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.
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.
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.
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.
You could iterate over the values of the Map
:
ArrayList<Object2> list = new ArrayList<>();
for (MyClass e : map.values()) {
list.add(e.objj);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With