You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:31:05