如何将 int[] 转换为 List在Java中?

发布于 2024-07-26 04:15:00 字数 165 浏览 6 评论 0原文

如何在 Java 中将 int[] 转换为 List

当然,除了逐项循环执行之外,我对任何其他答案都感兴趣。 但如果没有其他答案,我会选择这个答案作为最好的答案,以表明该功能不是 Java 的一部分。

How do I convert int[] into List<Integer> in Java?

Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the best to show the fact that this functionality is not part of Java.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

霊感 2024-08-02 04:15:00

  1. 在 Java 8+ 中,您可以创建 int 数组的流。 调用 Arrays.streamIntStream.of
  2. 调用 IntStream#boxed 使用从 int 原语到 Integer 对象。
  3. 使用 Stream.collect( Collectors.toList() ) 收集到列表中。 或者更简单地在 Java 16+ 中,调用 Stream#toList()

示例:

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

在 Java 16 及更高版本中:

List<Integer> list = Arrays.stream(ints).boxed().toList();

Streams

  1. In Java 8+ you can make a stream of your int array. Call either Arrays.stream or IntStream.of.
  2. Call IntStream#boxed to use boxing conversion from int primitive to Integer objects.
  3. Collect into a list using Stream.collect( Collectors.toList() ). Or more simply in Java 16+, call Stream#toList().

Example:

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

In Java 16 and later:

List<Integer> list = Arrays.stream(ints).boxed().toList();
夏の忆 2024-08-02 04:15:00

没有从 int[] 转换为 List 的快捷方式,因为 Arrays.asList 不处理装箱,只会创建一个List 这不是你想要的。 你必须制定一个实用方法。

int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
    intList.add(i);
}

There is no shortcut for converting from int[] to List<Integer> as Arrays.asList does not deal with boxing and will just create a List<int[]> which is not what you want. You have to make a utility method.

int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
    intList.add(i);
}
兔姬 2024-08-02 04:15:00

同样来自番石榴库。 .. com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)

Also from guava libraries... com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)
じ违心 2024-08-02 04:15:00

Arrays.asList 将无法像其他一些答案所期望的那样工作。

此代码将不会创建包含 10 个整数的列表。 它将打印 1,而不是 10

int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());

这将创建一个整数列表:

List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

如果您已经有了整数数组,则没有快速转换方法,您需要最好用循环。

另一方面,如果您的数组中有对象,而不是基元,则 Arrays.asList 将起作用:

String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);

Arrays.asList will not work as some of the other answers expect.

This code will not create a list of 10 integers. It will print 1, not 10:

int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());

This will create a list of integers:

List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

If you already have the array of ints, there is not quick way to convert, you're better off with the loop.

On the other hand, if your array has Objects, not primitives in it, Arrays.asList will work:

String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);
鹤舞 2024-08-02 04:15:00

我将用不同的方法添加另一个答案; 没有循环,而是一个将利用自动装箱功能的匿名类:

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; }
    };
}

I'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:

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; }
    };
}
放低过去 2024-08-02 04:15:00

最小的代码是:

public List<Integer> myWork(int[] array) {
    return Arrays.asList(ArrayUtils.toObject(array));
}

其中 ArrayUtils 来自 commons-lang :)

The smallest piece of code would be:

public List<Integer> myWork(int[] array) {
    return Arrays.asList(ArrayUtils.toObject(array));
}

where ArrayUtils comes from commons-lang :)

与往事干杯 2024-08-02 04:15:00

在 Java 8 中使用流:

int[] ints = {1, 2, 3};
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));

或使用收集器

List<Integer> list =  Arrays.stream(ints).boxed().collect(Collectors.toList());

In Java 8 with stream:

int[] ints = {1, 2, 3};
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));

or with Collectors

List<Integer> list =  Arrays.stream(ints).boxed().collect(Collectors.toList());
风透绣罗衣 2024-08-02 04:15:00

在 Java 8 中:

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());

In Java 8 :

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
南薇 2024-08-02 04:15:00

如果您使用的是java 8,我们可以使用流API将其转换为列表。

List<Integer> list = Arrays.stream(arr)     // IntStream 
                                .boxed()        // Stream<Integer>
                                .collect(Collectors.toList());

您也可以使用 IntStream 进行转换。

List<Integer> list = IntStream.of(arr) // return Intstream
                                    .boxed()        // Stream<Integer>
                                    .collect(Collectors.toList());

还有其他外部库,例如 guava 和 apache commons
也可以将其转换。

干杯。

If you are using java 8, we can use the stream API to convert it into a list.

List<Integer> list = Arrays.stream(arr)     // IntStream 
                                .boxed()        // Stream<Integer>
                                .collect(Collectors.toList());

You can also use the IntStream to convert as well.

List<Integer> list = IntStream.of(arr) // return Intstream
                                    .boxed()        // Stream<Integer>
                                    .collect(Collectors.toList());

There are other external library like guava and apache commons
also available convert it.

cheers.

泅人 2024-08-02 04:15:00

还值得查看此错误报告,该报告已关闭,原因是“不”一个缺陷”和以下文本:

“整个数组的自动装箱不是指定的行为,这是有充分理由的。
对于大型阵列来说,它的成本可能高得令人望而却步。”

It's also worth checking out this bug report, which was closed with reason "Not a defect" and the following text:

"Autoboxing of entire arrays is not specified behavior, for good reason.
It can be prohibitively expensive for large arrays."

美人骨 2024-08-02 04:15:00
int[] arr = { 1, 2, 3, 4, 5 };

List<Integer> list = Arrays.stream(arr)     // IntStream
                            .boxed()        // Stream<Integer>
                            .collect(Collectors.toList());

请参阅

int[] arr = { 1, 2, 3, 4, 5 };

List<Integer> list = Arrays.stream(arr)     // IntStream
                            .boxed()        // Stream<Integer>
                            .collect(Collectors.toList());

see this

你不是我要的菜∠ 2024-08-02 04:15:00

尝试一下这个类:

class PrimitiveWrapper<T> extends AbstractList<T> {

    private final T[] data;

    private PrimitiveWrapper(T[] data) {
        this.data = data; // you can clone this array for preventing aliasing
    }

    public static <T> List<T> ofIntegers(int... data) {
        return new PrimitiveWrapper(toBoxedArray(Integer.class, data));
    }

    public static <T> List<T> ofCharacters(char... data) {
        return new PrimitiveWrapper(toBoxedArray(Character.class, data));
    }

    public static <T> List<T> ofDoubles(double... data) {
        return new PrimitiveWrapper(toBoxedArray(Double.class, data));
    }  

    // ditto for byte, float, boolean, long

    private static <T> T[] toBoxedArray(Class<T> boxClass, Object components) {
        final int length = Array.getLength(components);
        Object res = Array.newInstance(boxClass, length);

        for (int i = 0; i < length; i++) {
            Array.set(res, i, Array.get(components, i));
        }

        return (T[]) res;
    }

    @Override
    public T get(int index) {
        return data[index];
    }

    @Override
    public int size() {
        return data.length;
    }
}

测试用例:

List<Integer> ints = PrimitiveWrapper.ofIntegers(10, 20);
List<Double> doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc

give a try to this class:

class PrimitiveWrapper<T> extends AbstractList<T> {

    private final T[] data;

    private PrimitiveWrapper(T[] data) {
        this.data = data; // you can clone this array for preventing aliasing
    }

    public static <T> List<T> ofIntegers(int... data) {
        return new PrimitiveWrapper(toBoxedArray(Integer.class, data));
    }

    public static <T> List<T> ofCharacters(char... data) {
        return new PrimitiveWrapper(toBoxedArray(Character.class, data));
    }

    public static <T> List<T> ofDoubles(double... data) {
        return new PrimitiveWrapper(toBoxedArray(Double.class, data));
    }  

    // ditto for byte, float, boolean, long

    private static <T> T[] toBoxedArray(Class<T> boxClass, Object components) {
        final int length = Array.getLength(components);
        Object res = Array.newInstance(boxClass, length);

        for (int i = 0; i < length; i++) {
            Array.set(res, i, Array.get(components, i));
        }

        return (T[]) res;
    }

    @Override
    public T get(int index) {
        return data[index];
    }

    @Override
    public int size() {
        return data.length;
    }
}

testcase:

List<Integer> ints = PrimitiveWrapper.ofIntegers(10, 20);
List<Double> doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc
月亮邮递员 2024-08-02 04:15:00

最好的镜头:

    /**
     * Integer modifiable fixed length list of an int array or many int's.
     *
     * @author Daniel De Leon.
     */
    public class IntegerListWrap extends AbstractList<Integer> {
    
        int[] data;
    
        public IntegerListWrap(int... data) {
            this.data = data;
        }
    
        @Override
        public Integer get(int index) {
            return data[index];
        }
    
        @Override
        public Integer set(int index, Integer element) {
            int r = data[index];
            data[index] = element;
            return r;
        }
    
        @Override
        public int size() {
            return data.length;
        }
    }
  • 支持get和set。
  • 无内存数据重复。
  • 不会在循环中浪费时间。

例子:

int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);

The best shot:

    /**
     * Integer modifiable fixed length list of an int array or many int's.
     *
     * @author Daniel De Leon.
     */
    public class IntegerListWrap extends AbstractList<Integer> {
    
        int[] data;
    
        public IntegerListWrap(int... data) {
            this.data = data;
        }
    
        @Override
        public Integer get(int index) {
            return data[index];
        }
    
        @Override
        public Integer set(int index, Integer element) {
            int r = data[index];
            data[index] = element;
            return r;
        }
    
        @Override
        public int size() {
            return data.length;
        }
    }
  • Support get and set.
  • No memory data duplication.
  • No wasting time in loops.

Examples:

int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);
花间憩 2024-08-02 04:15:00

这是另一种可能性,同样是 Java 8 Streams:

void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
    IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}

Here is another possibility, again with Java 8 Streams:

void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
    IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}
向日葵 2024-08-02 04:15:00

那这个呢:

int[] a = {1,2,3};
Integer[] b = ArrayUtils.toObject(a);
List<Integer> c = Arrays.asList(b);

What about this:

int[] a = {1,2,3};
Integer[] b = ArrayUtils.toObject(a);
List<Integer> c = Arrays.asList(b);
静水深流 2024-08-02 04:15:00

如果您愿意使用第三方库,这将适用于 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 的提交者。

If you're open to using a third party library, this will work in 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);

Note: I am a committer for Eclipse Collections.

长梦不多时 2024-08-02 04:15:00
   /* Integer[] to List<Integer> */



        Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        List<Integer> arrList = new ArrayList<>();
        arrList.addAll(Arrays.asList(intArr));
        System.out.println(arrList);


/* Integer[] to Collection<Integer> */


    Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
    Collection<Integer> c = Arrays.asList(intArr);
   /* Integer[] to List<Integer> */



        Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        List<Integer> arrList = new ArrayList<>();
        arrList.addAll(Arrays.asList(intArr));
        System.out.println(arrList);


/* Integer[] to Collection<Integer> */


    Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
    Collection<Integer> c = Arrays.asList(intArr);
可遇━不可求 2024-08-02 04:15:00

这是一个解决方案:

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]

Here is a solution:

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);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
酒几许 2024-08-02 04:15:00

您可以使用 IntStream of 并将其装箱为 Integer,然后使用反向比较器进行排序。

List<Integer> listItems = IntStream.of(arrayItems)
                .boxed()
                .sorted(Collections.reverseOrder())
                .collect(Collectors.toList());

这种方法的优点是更加灵活,因为您可以使用不同的收集器来创建不同类型的列表(例如,ArrayList、LinkedList 等)。

You could use IntStream of and boxed it to Integer after that sorted using reverseOrder comparator.

List<Integer> listItems = IntStream.of(arrayItems)
                .boxed()
                .sorted(Collections.reverseOrder())
                .collect(Collectors.toList());

This approach has the advantage of being more flexible, as you can use different collectors to create different types of lists (e.g., an ArrayList, a LinkedList, etc.).

那请放手 2024-08-02 04:15:00

这是将数组转换为 ArrayList 的通用

<T> ArrayList<T> toArrayList(Object o, Class<T> type){
    ArrayList<T> objects = new ArrayList<>();
    for (int i = 0; i < Array.getLength(o); i++) {
        //noinspection unchecked
        objects.add((T) Array.get(o, i));
    }
    return objects;
}

方法

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);

Here is a generic way to convert array to ArrayList

<T> ArrayList<T> toArrayList(Object o, Class<T> type){
    ArrayList<T> objects = new ArrayList<>();
    for (int i = 0; i < Array.getLength(o); i++) {
        //noinspection unchecked
        objects.add((T) Array.get(o, i));
    }
    return objects;
}

Usage

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
暮凉 2024-08-02 04:15:00
Arrays.stream(ints).forEach(list::add);
Arrays.stream(ints).forEach(list::add);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文