How to convert int[] into List in Java?

后端 未结 20 2129
萌比男神i
萌比男神i 2020-11-22 06:18

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

Of course, I\'m interested in any other answer than doing it in a loop, item by it

相关标签:
20条回答
  • 2020-11-22 06:31

    Streams

    In Java 8 you can do this

    int[] ints = {1,2,3};
    List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-22 06:31

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

    0 讨论(0)
  • 2020-11-22 06:31
    int[] arr = { 1, 2, 3, 4, 5 };
    
    List<Integer> list = Arrays.stream(arr)     // IntStream
                                .boxed()        // Stream<Integer>
                                .collect(Collectors.toList());
    

    see this

    0 讨论(0)
  • 2020-11-22 06:31

    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.

    0 讨论(0)
  • 2020-11-22 06:32

    The best shot:

    **
     * Integer modifiable fix 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);
    
    0 讨论(0)
  • 2020-11-22 06:34

    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; }
        };
    }
    
    0 讨论(0)
提交回复
热议问题