Organizational Research By

Surprising Reserch Topic

convert a Map to List in Java?


What is the best way to convert a Map to a List? Just iterate over all values and insert them in a list or am I overlooking something?

asked Jun 22, 2015 in Core java by rahulgii
0 votes
108 views



Related Hot Questions

3 Answers

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

assuming:

Map<Key,Value> map;
answered Jun 22, 2015 by rahulgii
0 votes
The issue here is that Map has two values (a key and value), while a List only has one value (an element).

Therefore, the best that can be done is to either get a List of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).

Say we have a Map:

Map m = new HashMap();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");
The keys as a List can be obtained by creating a new ArrayList from a Set returned by the Map.keySet method:

List list = new ArrayList(m.keySet());
While the values as a List can be obtained creating a new ArrayList from a Collection returned by the Map.values method:

List list = new ArrayList(m.values());
The result of getting the List of keys:

Apple
Another
Hello
The result of getting the List of values:

3.14
Element
World
answered Jun 22, 2015 by rahulgii
0 votes
Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("java", 20);
    map.put("C++", 45);

    Set <Entry<String, Integer>> set = map.entrySet();

    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);

we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.

answered Jun 22, 2015 by rahulgii

...