How to convert the map <K, V> to two lists while maintaining order?

How to convert Map<K, V>in the list List<K> keys, List<V> valuesto order in keysand valuesmatched? 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 right that I have to manually convert them or is there a shortcut somewhere?

Update: thanks to the answers, I was able to find additional useful information that I would like to share with you, a random google user: How to efficiently iterate over each entry on the map?

+5
source share
4 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());
}
+10
source

, , :

List<String keys = new ArrayList<String>(map.keySet());
List<String> values = new ArrayList<String>();
for(String key: keys) {
    values.add(map.get(key));
}
+1
+1

Please note: the map is not an ordered collection. The iteration order is not fixed. As you add more entries to your map, they will appear at random points in the iteration and therefore will no longer match any of the lists you created.

If you need the iteration order of the map to be the same as the insertion order than look at LinkedHashMap

+1
source

All Articles