English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在该程序中,您将学习将Java map集合转换为列表的各种技巧。
import java.util.*; public class MapList { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); 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("Lista de claves: " + ); System.out.println("Lista de valores: " + ); } }
运行该程序时,输出为:
Key List: [1, 2, 3, 4, 5] Value List: [a, b, c, d, e]
在上面的程序中,我们有一个名为的Integer和String的map集合。由于map包含键值对,因此我们需要两个列表来存储它们,即keyList键和valueList值。
我们使用map的keySet()方法获取所有键,并从它们创建了一个ArrayList keyList。 同样,我们使用map的values()方法获取所有值,并从中创建一个ArrayList valueList。
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, "a"); 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("Lista de claves: " + ); System.out.println("Lista de valores: " + ); } }
La salida del programa es similar a la1Iguales.
En el programa anterior, no hemos utilizado el constructor de ArrayList, sino que hemos convertido el mapeo en una lista utilizando stream()
Hemos pasado toList() del Collector como parámetro, convirtiendo las claves y valores en un flujo mediante el método collect() y luego en una lista