Java类型转换—— int[] 、 Integer[] 、 List 之间的转化

Java类型转换——int[]Integer[]List之间的转化

直接上代码,设计到Java 8新特性Stream,并测试一下效率:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Test01 {
public static void main(String[] args) {
long s = System.currentTimeMillis();
List<Integer> nums = Stream.generate(Math::random)
.map(a -> new Integer((int)(a * 100000)))
.limit(10000000)
.collect(toList());

System.out.println("随机列表大小为:" + nums.size());
System.out.println("生成花费时间:" + (System.currentTimeMillis() - s) / 1000.0 + "s");

//List转int[]
s = System.currentTimeMillis();
int[] listToInt = nums.stream()
.mapToInt(Integer::intValue)
.toArray();
System.out.println("List转int[]:" + (System.currentTimeMillis() - s) / 1000.0 + "s");

//list转Integer[]
s = System.currentTimeMillis();
Integer[] listToInteger = nums.toArray(new Integer[nums.size()]);
System.out.println("list转Integer[]:" + (System.currentTimeMillis() - s) / 1000.0 + "s");

//int[]转List
s = System.currentTimeMillis();
List<Integer> intToList = Arrays.stream(listToInt) //返回一个IntStream
.boxed() //装箱返回一个普通Stream
.collect(toList()); //将Stream归约成List
System.out.println("int[]转List:" + (System.currentTimeMillis() - s) / 1000.0 + "s");

//int[]转Integer[]
s = System.currentTimeMillis();
Integer[] intToInteger = Arrays.stream(listToInt) //返回一个IntStream
.boxed()
.toArray(Integer[]::new);
System.out.println("int[]转Integer[]:" + (System.currentTimeMillis() - s) / 1000.0 + "s");

//Integer[]转list
s = System.currentTimeMillis();
List<Integer> integerToList = new ArrayList<>(Arrays.asList(listToInteger));
System.out.println("Integer[]转list:" + (System.currentTimeMillis() - s) / 1000.0 + "s");

//Integer[]转int[]
s = System.currentTimeMillis();
int[] integerToInt = Arrays.stream(listToInteger) //返回一个Stream<Integer>
.mapToInt(Integer::intValue) //转换成一个IntStream
.toArray(); //转化成数组
System.out.println("Integer[]转int[]:" + (System.currentTimeMillis() - s) / 1000.0 + "s");
}
}

输出结果为:

1
2
3
4
5
6
7
8
随机列表大小为:10000000
生成花费时间:3.705s
List转int[]:2.593s
list转Integer[]:0.046s
int[]转List:3.473s
int[]转Integer[]:0.864s
Integer[]转list:0.318s
Integer[]转int[]:0.037s

总结:对于效率测试,一千万的数据量我们发现除了int[]List之间的转换,其余的都很快、在1s内完成