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?
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());
}
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));
}
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