首先,让我们创建一个Java Map并初始化-
Map<Integer, String> map = new HashMap<>(); map.put(1, "Tom"); map.put(2, "John"); map.put(3, "Kevin"); map.put(4, "Jacob"); map.put(5, "Ryan");
现在,将Map转换为List-
ArrayList<Integer> key = new ArrayList<Integer>(map.keySet()); ArrayList<String> value = new ArrayList<String>(map.values());
以下是在Java中将Maps转换为List的程序-
import java.util.HashMap; import java.util.ArrayList; import java.util.Map; public class Demo { public static void main(String args[]) { Map<Integer, String> map = new HashMap<>(); map.put(1, "Tom"); map.put(2, "John"); map.put(3, "Kevin"); map.put(4, "Jacob"); map.put(5, "Ryan"); map.put(6, "Bradley"); map.put(7, "Andy"); map.put(8, "Tim"); System.out.println("HashMap = " + map); ArrayList<Integer> key = new ArrayList<Integer>(map.keySet()); ArrayList<String> value = new ArrayList<String>(map.values()); System.out.println("\nList (Map Keys) = "+key); System.out.println("List (Map Values) = "+value); } }
输出结果
HashMap = {1=Tom, 2=John, 3=Kevin, 4=Jacob, 5=Ryan, 6=Bradley, 7=Andy, 8=Tim} List (Map Keys) = [1, 2, 3, 4, 5, 6, 7, 8] List (Map Values) = [Tom, John, Kevin, Jacob, Ryan, Bradley, Andy, Tim]