5

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?

Community
  • 1
  • 1
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137

4 Answers4

10

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());
}
mR_fr0g
  • 8,462
  • 7
  • 39
  • 54
rongenre
  • 1,334
  • 11
  • 21
1

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));
}
Avi
  • 21,182
  • 26
  • 82
  • 121
1

You could iterate over map.entrySet(), appending the keys and values to the two lists.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Please note that Map is not an ordered Collection. The iteration order is not fixed. So as you add more entries into your Map they will appear at random points in the iteration and thus will no longer match any lists you created.

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

mR_fr0g
  • 8,462
  • 7
  • 39
  • 54
  • I do not care about the order, except that I need a pair (key, value) at the same "position" in the two resulting lists. – Micha Wiedenmann Apr 08 '13 at 14:21
  • Doesn't this do the `iterator`? True, you can't be sure in which order the map is, but you can make sure that when iterating through the `entrySet` the `Iterator` iterates in a specific order. – GameDroids Apr 08 '13 at 14:22
  • @MichaWiedenmann: well then you have nothing to worry about when putting the values in your two lists. Just take special care when altering the lists afterwards. – GameDroids Apr 08 '13 at 14:24