How to convert int[] into List in Java?

后端 未结 20 2132
萌比男神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:43

    In Java 8 :

    int[] arr = {1,2,3};
    IntStream.of(arr).boxed().collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-22 06:44

    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.

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

    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);
    
    0 讨论(0)
  • 2020-11-22 06:48

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 06:49

    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."

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

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