我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
当前回答
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
看到这个
其他回答
也来自番石榴图书馆…com.google.common.primitives.Ints:
List<Integer> Ints.asList(int...)
这里有一个解决方案:
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));
List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
在Java 8中:
int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
那么这个呢:
Int [] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
看到这个