如何将int、long、double基本类型数组转换为Map集合?
如何将int类型数组转换为Map<Integer, String>集合
针对你给出的场景,我们可以利用Java 8+的Stream API高效实现int数组到Map的转换,核心是通过IntStream处理基本类型数组,结合Collectors.toMap完成键值映射。
完整实现代码
import java.util.*; import java.util.stream.*; public class PrimitiveStreamCollection { private static final String[] words = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; private static final int[] numbers = { 8, 6, 7, 5, 3, 0, 9 }; public static Map<Integer, String> collect(int[] values) { return Arrays.stream(values) .boxed() .collect(Collectors.toMap( num -> num, num -> words[num] )); } public static void main(String[] args) { Map<Integer, String> map = collect(numbers); System.out.println(map); // 输出:{0=zero, 3=three, 5=five, 6=six, 7=seven, 8=eight, 9=nine} } }
代码说明
Arrays.stream(values):将int数组转换为IntStream,专门处理int基本类型流,比普通Stream更高效。boxed():把流中的int基本类型自动包装为Integer对象,满足Map键的引用类型要求。Collectors.toMap(...):- 第一个参数
num -> num:指定Map的键为数组中的数值本身。 - 第二个参数
num -> words[num]:利用数值作为索引,从words数组中取出对应的英文数字字符串作为Map的值。
- 第一个参数
处理重复值的扩展
如果输入的int数组存在重复数值,直接使用toMap会抛出IllegalStateException。此时可以添加第三个参数处理冲突,比如保留第一个出现的值:
.collect(Collectors.toMap( num -> num, num -> words[num], (existingValue, newValue) -> existingValue ));
其他基本类型数组的转换思路
对于long/double数组,处理逻辑一致:
- long数组:用
Arrays.stream(longArray).boxed()转为Stream<Long>,再通过toMap完成映射。 - double数组:用
Arrays.stream(doubleArray).boxed()转为Stream<Double>,再执行映射逻辑。
内容的提问来源于stack exchange,提问作者Mr. Polywhirl
相关产品推荐
相关产品推荐

