
本文介绍了如何将 Java 中的原始类型数组(如 `int[]`, `long[]`, `double[]`)转换为 `Map` 集合。主要讲解了两种方法:一种是通过将原始类型“装箱”为对应的包装类,然后使用 `Collectors.toMap` 进行收集;另一种是直接使用原始类型流的 `collect` 方法,自定义收集器的行为。通过示例代码,详细展示了两种方法的实现方式及各自的特点。
在 Java 中,将原始类型数组转换为 Map 集合是一个常见的需求。由于原始类型(如 int, long, double)与对象类型(如 Integer, Long, Double)在 Stream 处理上存在差异,因此需要采用不同的方法来实现。本文将详细介绍两种常用的方法:使用装箱(Boxing)和使用原始类型流的 collect 方法。
装箱是指将原始类型转换为对应的包装类。Java 提供了自动装箱和拆箱的机制,方便原始类型和包装类之间的转换。
以下是一个示例代码,演示如何将 int[] 转换为 Map<Integer, String>:
import java.util.*;
import java.util.function.*;
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> collectBoxed(int[] values) {
return Arrays.stream(values)
.boxed()
.collect(
Collectors.toMap(
Function.identity(),
value -> words[value]));
}
public static void main(String[] args) {
Map<Integer, String> boxedMap = collectBoxed(numbers);
System.out.println(boxedMap);
}
}代码解释:
IntStream, LongStream, DoubleStream 等原始类型流提供了 collect 方法,该方法允许自定义收集器的行为,无需进行装箱操作,从而提高性能。
collect 方法接收三个参数:
以下是一个示例代码,演示如何使用原始类型流的 collect 方法将 int[] 转换为 Map<Integer, String>:
import java.util.*;
import java.util.function.*;
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> collectUnboxed(int[] values) {
return Arrays.stream(values)
.collect(
HashMap::new,
(acc, value) -> acc.put(value, words[value]),
HashMap::putAll);
}
public static void main(String[] args) {
Map<Integer, String> unboxedMap = collectUnboxed(numbers);
System.out.println(unboxedMap);
}
}代码解释:
本文介绍了两种将原始类型数组转换为 Map 集合的方法:使用装箱和使用原始类型流的 collect 方法。
在实际应用中,应根据具体的需求和性能要求选择合适的方法。如果对性能要求不高,可以使用装箱方法;如果需要处理大量数据,建议使用原始类型流的 collect 方法。
以上就是将原始类型数组的值收集到 Map 集合中的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号