3

Is there anyone who knows how to convert a Map to a List

I found here something like this :

List<Value> list = new ArrayList<Value>(map.values());

But this is going to store just the value of the Map to the List

What I want to do is : copy the Key & the Value to the List

So, do you know how to achieve this ?

Wassim AZIRAR
  • 10,577
  • 37
  • 118
  • 171

4 Answers4

9

This will give you a List of the Map entries:

List<Map.Entry<Key, Value>> list = 
    new ArrayList<Map.Entry<Key, Value>>(map.entrySet());

FYI, entries have a getKey() and a getValue() method.

Bohemian
  • 389,931
  • 88
  • 552
  • 692
3

One way you can do is Create a List with adding all the keys like :

List list = new ArrayList(map.keySet());

Then add all the values like :

 list.addAll(map.values);

And then probably you have to access with index like: if map size is 10 , you know that you have 20 elements in the list. So you have to write a logic to access the key-value from the list with proper calculation of index like: size/2 something like that. I am not sure if that helps what your requirement is.

Swagatika
  • 3,306
  • 6
  • 29
  • 38
2

Try storing the Map.Entrys of the map:

new ArrayList<Entry<Key, Value>>(map.entrySet());

Example:

public static void main(String[] args) {

    Map<String, Integer> map = new HashMap<String, Integer>();

    map.put("Hello", 0);
    map.put("World!", 1);

    ArrayList<Entry<String, Integer>> list =
        new ArrayList<Entry<String, Integer>>(map.entrySet());

    System.out.println(list.get(0).getKey() + " -> " + list.get(0).getValue());
}
dacwe
  • 42,413
  • 12
  • 112
  • 138
2

Both @Bohemian and @dacwe are right. I'd say moreover: in most cases you do not have to create your own list. Just use map.entrySet(). It returns Set, but Set is just a Collection that allows iterating over its elements. Iterating is enough in 95% of cases.

AlexR
  • 111,884
  • 15
  • 126
  • 200