Java Program to Convert Map (HashMap) to List

Updated on December 12, 2024
Convert map (hashmap) to list header image

Introduction

In Java, maps and lists are two of the most commonly used data structures in the collections framework. Maps, such as HashMap, store items in key-value pairs, whereas lists store items in an ordered sequence. There are scenarios in software development where you might need to convert a Map to a List. For example, you might want to sort the keys or values of a map, or perhaps you need a list representation for APIs that require a list input.

In this article, you will learn how to convert a Map (specifically HashMap) into a List. Gain insights into extracting either keys, values, or both from a map and storing them into a List. Demonstrate the conversion process through practical coding examples that you can readily implement in your projects.

Extracting Keys from a Map

Convert Map Keys to List

  1. Create a HashMap and populate it with sample data.

  2. Utilize the keySet() method to extract the keys, then construct a List using the ArrayList constructor.

    java
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            Map<String, Integer> map = new HashMap<>();
            map.put("one", 1);
            map.put("two", 2);
            map.put("three", 3);
    
            List<String> keysList = new ArrayList<>(map.keySet());
            System.out.println(keysList);
        }
    }
    

    The code above creates a HashMap and retrieves the keys using the keySet() method. These keys are then stored in an ArrayList, which is subsequently printed.

Extracting Values from a Map

Convert Map Values to List

  1. Initialize a HashMap and include some key-value pairs.

  2. Use the values() method to get the values from the map and direct these into a new ArrayList.

    java
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            Map<String, Integer> map = new HashMap<>();
            map.put("a", 100);
            map.put("b", 200);
            map.put("c", 300);
    
            List<Integer> valuesList = new ArrayList<>(map.values());
            System.out.println(valuesList);
        }
    }
    

    In this snippet, values() is called on the HashMap to obtain a collection of values, which are then stored in an ArrayList.

Extracting Both Keys and Values

Convert Both Keys and Values to List of Entries

  1. Start with a populated HashMap.

  2. Use the entrySet() method to get the set of entries.

  3. Stream the entries to convert each entry to a custom object or a string representation.

    java
    import java.util.*;
    import java.util.stream.Collectors;
    
    public class Main {
        public static void main(String[] args) {
            Map<String, Integer> map = new HashMap<>();
            map.put("x", 24);
            map.put("y", 25);
            map.put("z", 26);
    
            List<String> entriesList = map.entrySet()
                                          .stream()
                                          .map(entry -> entry.getKey() + "=" + entry.getValue())
                                          .collect(Collectors.toList());
            System.out.println(entriesList);
        }
    }
    

    This example uses Java Streams to transform each map entry into a string combining key and value, and then collects these strings into a list.

Conclusion

Converting a HashMap to a List in Java is a straightforward process thanks to the collections framework and Java Stream API. Depending on whether you need keys, values, or both in list form, Java provides efficient methods such as keySet(), values(), and entrySet() to aid in these conversions. By following the demonstrated examples, you enhance your ability to manipulate and adapt data structures in Java, ensuring your code is versatile and capable of meeting various functional requirements. Whether for data manipulation, API interaction, or any other reason, mastering these conversions prepares you to handle diverse programming challenges effectively.