Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

How do I convert a Map to a List? There are two scenarios: one is to convert a key in a Map to a List, and the other is to convert a value in a Map to a List


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main2Test {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1."1a");
        map.put(2."2b");
        map.put(3."3c");
        map.put(3."3d");
        map.put(4."4a");

        List<Integer> keyList = new ArrayList(map.keySet());
        for (Integer tmp : keyList) {
            System.out.println(tmp);
        }

        List<String> valueList = new ArrayList<>(map.values());
        for(String tmp : valueList) { System.out.println(tmp); }}}Copy the code