Explain Codes LogoExplain Codes Logo

How do I convert a Map to List in Java?

java
map-to-list
streams
java-8
Alex KataevbyAlex Kataev·Aug 12, 2024
TLDR
List<ValueType> list = new ArrayList<>(map.values());

The above line efficiently transforms a Map into a List. The map.values() are passed directly into the ArrayList constructor, a maneuver that harvests the values and populates the list. No duplicates are left behind—like cookies, duplicates make every list better!

Nuts and bolts: using streams for advanced conversions

Are you tired of that plain old Map->List conversion? Want something new? Streams got you covered!

Canvassing values of the map into a list

List<ValueType> valueList = map.values().stream().collect(Collectors.toList());

A below-the-hood view of all the glitters: the values of your map will, now, be a list.

Converting keys of the map into a list

List<KeyType> keyList = map.keySet().stream().collect(Collectors.toList());

When everybody else is going for values, we go for keys. It's "hipster programming"! Now your map keys are a list. Remember with streams, you can do the extra lap: filter, sort or transform your data during the conversion.

Ordered or chaos: impact of map entry order on the conversion

Map to list conversions don't guarantee order of entries in the resulting list. It's pure chaos! Unless you wield the mighty tools of TreeMap or LinkedHashMap, which ensure every knight stands in order, either by sorting or maintaining the insertion order.

Practical Conversion Tips to Boost Your Code Efficiency

No value left behind: dealing with duplicates

List is a big fan of repetition. It collects all the values from your map, including the duplicates.

Map<String, Integer> fruitBasket = new HashMap<>(); fruitBasket.put("Apple", 1); fruitBasket.put("Banana", 2); fruitBasket.put("Cherry", 1); // A little gem that loves to surprise List<Integer> qtyList = new ArrayList<>(fruitBasket.values()); // qtyList: [1, 2, 1]

Sorted lists for Type As

To get a sorted list of keys or values from your map, use a TreeMap. It keeps everything tidy and organized:

Map<String, Integer> treeAgeMap = new TreeMap<>(); treeAgeMap.put("Willow", 75); // A weeping beauty treeAgeMap.put("Redwood", 1000); // Still doesn't need a walking stick treeAgeMap.put("Maple", 150); // Sweet and sappy // The keys will be sorted naturally: ["Maple", "Redwood", "Willow"] List<String> sortedTreeNames = new ArrayList<>(treeAgeMap.keySet());

The Java 8+ Stream API: transform your data on the go

In this brave new world of Java 8, you can stream keys and values with intermediate operations such as map, filter, or sorted:

List<Integer> sortedAges = ageMap.values() .stream() .sorted() .collect(Collectors.toList());

Just like an assembly line, this method provides convenient pipeline processing, transforming your data on the fly.