How do I convert a Map to List in Java?
You can use the entrySet()
method of the Map
interface to get a Set
view of the mappings contained in the map, and then create a List
from this set using the new ArrayList<>(set)
constructor.
Here's an example of how you can do this:
Map<String, Integer> map = new HashMap<>();
// add some mappings to the map
Set<Map.Entry<String, Integer>> set = map.entrySet();
List<Map.Entry<String, Integer>> list = new ArrayList<>(set);
Alternatively, you can use the values()
method of the Map
interface to get a Collection
view of the values contained in the map, and then create a List
from this collection using the new ArrayList<>(collection)
constructor.
Here's an example of how you can do this:
Map<String, Integer> map = new HashMap<>();
// add some mappings to the map
Collection<Integer> values = map.values();
List<Integer> list = new ArrayList<>(values);