Farmer
Farmer

Reputation: 10983

Converting a Map to a List

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 ?

Upvotes: 3

Views: 6009

Answers (4)

Swagatika
Swagatika

Reputation: 3436

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.

Upvotes: 3

dacwe
dacwe

Reputation: 43504

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

Upvotes: 2

AlexR
AlexR

Reputation: 115328

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.

Upvotes: 2

Bohemian
Bohemian

Reputation: 424993

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.

Upvotes: 9

Related Questions