How to convert int to Integer in java. This is the most popular question asked on the forums. Here are 3 examples of how to do this.
Convert using java streams (java 8+)
1 2 3 4 |
int[] data = {1,2,3,4,5,6,7,8,9,10}; Integer[] integerArrayFirst = Arrays.stream( data ).boxed().toArray( Integer[]::new ); Integer[] integerArraySecond = IntStream.of( data ).boxed().toArray( Integer[]::new ); |
Using regular for-loop without external libraries:
1 2 3 4 5 6 |
int[] primitiveArray = {1, 2, 3, 4, 5}; Integer[] objectArray = new Integer[primitiveArray.length]; for(int ctr = 0; ctr < primitiveArray.length; ctr++) { objectArray[ctr] = Integer.valueOf(primitiveArray[ctr]); // returns Integer value } |
Using Guava library
1 2 3 |
int[] primitives = {1,2,3}; List<Integer> boxed = Ints.asList(primitives); Integer[] boxedArray = Ints.asList(primitives).toArray(new Integer[]); |