Java
Map to List
programming
code conversion
data structures

How do I convert a Map to List in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Java, converting a Map to a List is a common task that you might encounter in various scenarios. This could be for ease of operation, API requirements, or merely data transformation purposes. A Map in Java is a data structure that stores key-value pairs, while a List is an ordered collection that stores elements. There are several methods to transform a Map into a List depending on what information from the map is required in the list (keys, values, or both).

Understanding Map and List Collections

Before delving into the conversion process, let's quickly understand the essential interfaces:

  • Map: Map<K, V> is an object that maps keys to values - without duplicate keys. Each key maps to exactly one value. The most commonly used implementations of Map interface are HashMap, TreeMap, and LinkedHashMap.
  • List: List<E> is an ordered collection (also known as a sequence). Lists can contain duplicate elements. Examples include ArrayList, LinkedList, and Vector.

Methods to Convert a Map to a List

1. Extracting Keys or Values Using Streams

In Java 8 and later, Streams provide a very convenient way to collect keys or values from a Map.

  • To Extract Keys:
java
  List<K> keyList = new ArrayList<>(map.keySet());
  • To Extract Values:
java
  List<V> valuesList = new ArrayList<>(map.values());

Using streams, this can alternatively be done as:

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

2. Converting Key-Value Pairs to List

Sometimes, you may need to store the key-value pairs themselves in a list, often as an entry set where each element in the list is a key-value pair:

java
List<Map.Entry<K, V>> entriesList = new ArrayList<>(map.entrySet());

Or using a stream:

java
List<Map.Entry<K, V>> entryList = map.entrySet().stream().collect(Collectors.toList());

3. Custom Class to Hold Key-Value Pairs

If you need more control or additional processing, you can define a custom class to hold the key-value data:

java
1public class KeyValuePair<K, V> {
2    private K key;
3    private V value;
4
5    // Constructor, getters and setters
6}
7
8List<KeyValuePair<K, V>> customList = map.entrySet().stream()
9    .map(entry -> new KeyValuePair<>(entry.getKey(), entry.getValue()))
10    .collect(Collectors.toList());

Applications and Considerations

  • Performance: Converting a map to a list, particularly with large datasets, should be considered within the context of performance. Streams provide a neat and concise approach but ensure to evaluate performance impacts, especially with complex processing inside streams.
  • Order: HashMap does not retain any order, whereas LinkedHashMap maintains the insertion order. Choice of List type (ArrayList vs. LinkedList) should also be considered based on subsequent operations (frequent insertions, deletions, random access, etc.).
  • Null Values: Be mindful of null keys and values; while certain maps and lists handle nulls, others might throw exceptions.

Summary Table

TaskCode Example
Extract KeysList<K> keyList = new ArrayList<>(map.keySet());
Extract ValuesList<V> valuesList = new ArrayList<>(map.values());
Extract EntriesList<Map.Entry<K, V>> entryList = new ArrayList<>(map.entrySet());
Advanced (Custom Object)// See the custom KeyValuePair class example above

Conclusion

Converting a Map to a List in Java can be done in several ways depending on the requirements—either by extracting keys, values, or both. Using Java 8 Streams can simplify the code and improve readability, but always consider the implications of data size and performance.


Course illustration
Course illustration

All Rights Reserved.