Java Map 转换为列表
首先,让我们创建一个 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 中将 Map 转换为 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("
List (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]
广告