我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
当前回答
如果你愿意使用第三方库,这将在Eclipse Collections中工作:
int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);
注意:我是Eclipse Collections的提交者。
其他回答
同样值得一看的是这个bug报告,它以“Not a defect”和以下文本结尾:
“自动装箱整个数组不是指定的行为,这是有充分理由的。 对于大型阵列来说,它可能会非常昂贵。”
Arrays.stream(ints).forEach(list::add);
你可以使用IntStream of并在使用reverseOrder比较器排序后将其装箱为Integer。
List<Integer> listItems = IntStream.of(arrayItems)
.boxed()
.sorted(Collections.reverseOrder())
.collect(Collectors.toList());
这种方法的优点是更加灵活,因为您可以使用不同的收集器来创建不同类型的列表(例如,ArrayList, LinkedList等)。
我将用不同的方法添加另一个答案;没有循环,而是一个匿名类,将利用自动装箱特性:
public List<Integer> asList(final int[] is)
{
return new AbstractList<Integer>() {
public Integer get(int i) { return is[i]; }
public int size() { return is.length; }
};
}
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
看到这个