Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int[] into List<Integer> in 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.

like image 681
pupeno Avatar asked Jul 02 '09 11:07

pupeno


People also ask

What does int [] do in Java?

Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].

How do you add an int array to an ArrayList in Java?

An array can be converted to an ArrayList using the following methods: Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.

How will you convert a list into an array of integers like int []?

We can use the Stream provided by Java 8 to convert a list of Integer to a primitive integer array in Java. We start by converting given List<Integer> to Stream<Integer> using List. stream() method. Now all we need to do is convert Stream<Integer> to int[] .


1 Answers

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(); 
like image 172
mikeyreilly Avatar answered Sep 28 '22 10:09

mikeyreilly