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, \ map.put(3, \ map.put(4, \ map.put(5, \ 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); } }
运行该程序时,输出为:
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, \ map.put(3, \ map.put(4, \ map.put(5, \ 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