20

I have a LinkedHashMap < String, String > map .

List < String > keyList;
List < String > valueList;
map.keySet();
map.values();

Is there an easy way to populate keyList from map.keySet() and valueList from map.values(), or do I have to iterate?

Razib
11.2k12 gold badges58 silver badges86 bronze badges
asked Dec 1, 2010 at 19:17

3 Answers 3

47

Most collections accept Collection as a constructor argument:

List<String> keyList = new ArrayList<String>(map.keySet());
List<String> valueList = new ArrayList<String>(map.values());
answered Dec 1, 2010 at 19:19
2
  • 2
    Both LinkedHashMap and List have an order, so I expect the desired result is that the Lists have the same order as the map. However, you use a Set as an intermediate type (the return value of map.keySet()), which does not have an order. As such, it is not guaranteed that keyList has the same order as map (note, though, that map.values() return a Collection rather than a Set, so it does not have a problem. [removed more about values() since it was based on me misunderstanding the documentation] Commented Jan 12, 2015 at 16:05
  • 3
    I was curious about map.keySet() and checked out the code. For LinkedHashMap this returns LinkedHashMap$LinkedKeySet, which DOES have a predictable order (that of the source LinkedHashMap), just like map.values(). So the above code will work as expected, and you end up with two lists where keyList[n] ==> valueList[n]. Commented Sep 4, 2015 at 14:56
7

For sure!

keyList.addAll(map.keySet());

Or you could pass it at the time of creation as well

List<String> keyList = new ArrayList<String>(map.KeySet());

http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

answered Dec 1, 2010 at 19:19
0

A different approach using java 8 -

List<String> valueList = map.values().stream().collect(Collectors.toList()); 
List<String> keyList = map.keySet().stream().collect(Collectors.toList()); 

Notes:

  • stream() - returns sequence of Object considering collection (here the map) as source

  • Collectors - Collectors are used to combining the result of processing on the elements of a stream.

answered Aug 7, 2019 at 13:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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