文
章
目
录
章
目
录
这个Java教程将教您如何将Map的键和值转换为数组、List或Set。Java中的Map是一组键值对。Map的键始终是唯一的,但可以具有重复的值。
1.将Map转换为数组
为了演示,让我们创建一个具有String键和Integer值的Map。
Map<String, Integer> map = Map.of("A",1, "B", 2, "C", 3);
Map.values()返回此Map中包含的值的集合视图。使用Collection.toArray()来从集合元素获取数组。这个方法需要返回数组的运行时类型。
Collection<Integer> values = map.values();
Integer valArray[] = values.toArray(new Integer[0]);
类似地,我们可以将Map的键收集到数组中。Map.keySet()返回Map中所有键的集合视图。使用Set.toArray(),我们可以将它转换为String数组。
String keyArray[] = map.keySet().toArray(new String[0]);
2.将Map转换为List
我们可以使用ArrayList构造函数将Map的值收集到列表中,该构造函数以值的集合作为其参数。
List<Integer> valList = new ArrayList<>(map.values());
我们可以使用Java Streams来实现相同的结果。
List<Integer> listOfValues = map.values().stream().collect(Collectors.toCollection(ArrayList::new));
同样,我们可以使用普通的Java和Streams将Map的键转换为List。
List<String> keyList = new ArrayList<>(map.keySet()); //ArrayList Constructor
List<String> listOfKeys = map.keySet().stream().collect(Collectors.toCollection(ArrayList::new)); //Streams
3.将Map转换为Set
我们可以使用HashSet构造函数或Streams将Map的值转换为集合。
//使用HashSet 构造函数
Set<Integer> valSet = new HashSet<>(map.values());
//使用Streams
Set<Integer> setOfValues = map.values().stream().collect(Collectors.toCollection(HashSet::new));
Map.keySet()返回Map中所有键的Set。
Set<String> keySet = map.keySet();
4.结论
这个教程教会了我们如何将Java Map的键和值转换为数组、List或Set,通过简单的示例。我们学会了使用ArrayList和HashSet构造函数以及Stream API。