示例 1: 将地图转换为列表
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("Key List: " + keyList); System.out.println("Value List: " + valueList); } }
输出
Key List: [1, 2, 3, 4, 5] Value List: [a, b, c, d, e]
在上面的程序中,我们有一个名为
map的整数和字符串的映射。由于
map 包含一个 key, value 对,我们需要两个列表来存储它们中的每一个,即
keyList 用于键和
valueList 用于值。
我们使用 map 的
keySet()
方法获取所有键并从中创建一个
ArrayList
keyList。同样,我们使用地图的
values()
方法获取所有值并从中创建一个
ArrayList
valueList。
示例 2: 使用流将 Map 转换为 List
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("Key List: " + keyList); System.out.println("Value List: " + valueList); } }
程序的输出与示例1相同。
在上面的程序中,我们没有使用
ArrayList
构造函数,而是使用
stream()
将映射转换为列表。
我们已经将键和值转换为流,并使用
collect()
方法传递
Collectors
'
toList()
将其转换为列表> 作为参数。