68

In Java, how does one get the values of a HashMap returned as a List?

sparkyspider
  • 13,195
  • 10
  • 89
  • 133
  • 1
    This probably should not be a question -- or you should turn it into a proper question and accept the first reasonable answer that comes along? It makes it harder to find a real question that needs answering. – michel-slm Mar 30 '11 at 07:42
  • 3
    If requirement to return a List is not a must, I think converting `Collection` or `Set` to `ArrayList` does not make much sense to me. Just return the collection or the Set that you get from HashMap – Nishant Mar 30 '11 at 07:44
  • 2
    duplicated: http://stackoverflow.com/questions/1026723/how-to-convert-a-map-to-list-in-java – Damian Leszczyński - Vash Mar 30 '11 at 07:55

8 Answers8

99
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
    System.out.println(s);
}
Péter Török
  • 114,404
  • 31
  • 268
  • 329
sparkyspider
  • 13,195
  • 10
  • 89
  • 133
  • 5
    Basically, the .values() method of the HashMap class returns a Collection of the values. You can also use .keys() for that matter. The ArrayList() class accepts a Collection as one of its constructors. Hence, you create a new ArrayList from a Collection of the HashMap values. I have no idea what the performance is like, but for me the simplicity is worth it! – sparkyspider Mar 30 '11 at 07:43
  • if you just want to print or get objects - you do not need to use List. – Nishant Mar 30 '11 at 07:47
  • Just putting that there to clarify. – sparkyspider Mar 30 '11 at 07:58
80

Assuming you have:

HashMap<Key, Value> map; // Assigned or populated somehow.

For a list of values:

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

For a list of keys:

List<Key> keys = new ArrayList<Key>(map.keySet());

Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.

maerics
  • 151,642
  • 46
  • 269
  • 291
  • 2
    +1 for noting proper ordering should use `LinkedHashMap` <=> `List`. Also, it's probably good practice for the unordered conversions to use `HashMap` <=> `Set` to indicate that it's unordered. – bcorso Aug 04 '15 at 18:57
  • 1
    Due to its simplicity, this appears to be a better solution than the answer chosen. – MAbraham1 Nov 24 '15 at 14:12
7

Collection Interface has 3 views

  • keySet
  • values
  • entrySet

Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct

My addition: How to convert "key-value pair" (aka entrySet)into list.

      Map m=new HashMap();
          m.put(3, "dev2");
          m.put(4, "dev3");

      List<Entry> entryList = new ArrayList<Entry>(m.entrySet());

      for (Entry s : entryList) {
        System.out.println(s);
      }

ArrayList has this constructor.

VedantK
  • 9,728
  • 7
  • 66
  • 71
7

Solution using Java 8 and Stream Api:

private static <K, V>  List<V> createListFromMapEntries (Map<K, V> map){
        return map.values().stream().collect(Collectors.toList());
    }

Usage:

  public static void main (String[] args)
    {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "one");
        map.put(2, "two");
        map.put(3, "three");

        List<String> result = createListFromMapEntries(map);
        result.forEach(System.out :: println);
    }
RichardK
  • 3,228
  • 5
  • 32
  • 52
7

Basically you should not mess the question with answer, because it is confusing.

Then you could specify what convert mean and pick one of this solution

List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));

List<String> valueList = Collections.list(Collections.enumeration(map.values()));
  • A `Map` has a `keySet()` method. Using that would be simpler than what you posted for the `keyList`. – Joachim Sauer Mar 30 '11 at 07:54
  • @Joachim, that is the correct method name that im thankful for. But if you want to convert the Set into list this is the way. – Damian Leszczyński - Vash Mar 30 '11 at 07:57
  • 1
    qVash: why? you can simply use `new ArrayList(map.keySet())` which is a more direct route and avoid creating an `Enumeration`. And I'm almost certain that it will perform better, because the `ArrayList` will be created with the correct size from the very beginning. – Joachim Sauer Mar 30 '11 at 07:59
  • Would this return a reference to the original values, and not a new set of objects? – sparkyspider Mar 30 '11 at 08:00
  • @Mark: the end effect is the same as what you posted: You'll have a new `ArrayList` referencing the same object that are also referenced by the `Map`. – Joachim Sauer Mar 30 '11 at 08:06
  • @Mark, if you refer to the values from map will do, but this solution seam to work slower than `new ArrayList(Collection col)` because there the table are copied to array at once using Arrays.copy function. – Damian Leszczyński - Vash Mar 30 '11 at 08:08
1

If you wanna maintain the same order in your list, say: your Map looks like:

map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")

and you want your list looks like

["msg1", "msg2", "msg3"]   // same order as the map

you will have to iterate through the Map:

// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)

List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
    list.add(entry.getKey(), entry.getValue());
}  
Shengjie
  • 12,336
  • 29
  • 98
  • 139
1

If you only want it to iterate over your HashMap, no need for a list:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
    System.out.println(s);
}

Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
    System.out.println(s);
}
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
0

I use usually map.values() to get values, then convert them to list

let say you have this Hashmap:

   HashMap<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

You can get values from the map, then convert them to a list in one code line like that:

 List<Integer> values = map.values().stream()
        .collect(Collectors.toList());
Ali Zedan
  • 285
  • 3
  • 17