Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Map<K, V> into two list while keeping the order?

Tags:

java

How can I convert a Map<K, V> into listsList<K> keys, List<V> values, such that the order in keys and values match? I can only find Set<K> Map#keySet() and Collection<V> Map#values() which I could convert to lists using:

List<String> keys   = new ArrayList<String>(map.keySet());
List<String> values = new ArrayList<String>(map.values());

but I worry that the order will be random.

Is it correct that I have to manually convert them or is there a shortcut somewhere?

Update: Owing to the answers I was able to find additional, useful information which I like to share with you, random google user: How to efficiently iterate over each Entry in a Map?

like image 997
Micha Wiedenmann Avatar asked Apr 08 '13 14:04

Micha Wiedenmann


2 Answers

Use Map.entrySet():

List<String> keys = new ArrayList<>(map.size());
List<String> values = new ArrayList<>(map.size());
for(Map.Entry<String, String> entry: map.entrySet()) {
   keys.add(entry.getKey());
   values.add(entry.getValue());
}
like image 106
rongenre Avatar answered Oct 11 '22 05:10

rongenre


You should extract the list of keys as you mentioned and then iterate over them and extract the values:

List<String keys = new ArrayList<String>(map.keySet());
List<String> values = new ArrayList<String>();
for(String key: keys) {
    values.add(map.get(key));
}
like image 42
Avi Avatar answered Oct 11 '22 06:10

Avi