69

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

3
  • 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. Commented Mar 30, 2011 at 7: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 Commented Mar 30, 2011 at 7:44
  • 2
    duplicated: stackoverflow.com/questions/1026723/… Commented Mar 30, 2011 at 7:55

8 Answers 8

102
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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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!
if you just want to print or get objects - you do not need to use List.
Just putting that there to clarify.
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.

2 Comments

+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.
Due to its simplicity, this appears to be a better solution than the answer chosen.
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()));

6 Comments

A Map has a keySet() method. Using that would be simpler than what you posted for the keyList.
@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.
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.
Would this return a reference to the original values, and not a new set of objects?
@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.
|
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.

Comments

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

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.