English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java program converts collections (HashMap) to lists

Comprehensive Java Examples

In this program, you will learn various techniques to convert Java map collections to lists.

Example1Convert map to list

import java.util.*;
public class MapList {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1});
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
        map.put(5, "e");
        List<Integer> keyList = new ArrayList<>(map.keySet());
        List<String> valueList = new ArrayList<>(map.values());
        System.out.println("Key List: ", + keyList);
        System.out.println("Value List: ", + valueList);
    }
}

When running the program, the output is:

Key List: [1, 2, 3, 4, 5]
Value List: [a, b, c, d, e]

In the above program, we have a map collection named Integer and String. Since the map containsKey-ValueYes, so we need two lists to store them, namely keyList for keys and valueList for values.

We use the map's keySet() method to get all keys and create an ArrayList keyList from them. Similarly, we use the map's values() method to get all values and create an ArrayList valueList from them.

Example2Use streams to convert the map to a list

import java.util.*;
import java.util.stream.Collectors;
public class MapList {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1});
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
        map.put(5, "e");
        List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());
        List<String> valueList = map.values().stream().collect(Collectors.toList());
        System.out.println("Key List: ", + keyList);
        System.out.println("Value List: ", + valueList);
    }
}

The output of this program is similar to the example1The same.

In the above program, we did not use the ArrayList constructor but used stream() to convert the map to a list

We have passed to the toList() of Collector as a parameter, converted the key and value to a stream through the collect() method, and then converted it to a list

Comprehensive Java Examples