Thursday, 2 January 2020

How to convert int[] to Integer[] in Java?


Approach 1: Traversing to each element and convert.
public static Integer[] getBoxedArray_approach1(int[] arr) {
	if (arr == null)
		return null;

	Integer[] result = new Integer[arr.length];
	int index = 0;
	for (int i : arr) {
		result[index] = Integer.valueOf(i);
		index++;
	}
	return result;
}

Approach 2: Using ‘Arrays.stream’.
Integer[] result = Arrays.stream(arr).boxed().toArray(Integer[]::new);

Approach 3: Using IntStream.
Integer[] result = IntStream.of(arr).boxed().toArray(Integer[]::new);

Find the below working application.


App.java
package com.sample.app;

import java.io.IOException;
import java.util.Arrays;
import java.util.stream.IntStream;

public class App {

	private static void printElements(Integer[] arr) {
		for (int i : arr) {
			System.out.print(i + " ");
		}
		System.out.println();
	}

	public static Integer[] getBoxedArray_approach1(int[] arr) {
		if (arr == null)
			return null;

		Integer[] result = new Integer[arr.length];
		int index = 0;
		for (int i : arr) {
			result[index] = Integer.valueOf(i);
			index++;
		}
		return result;
	}

	public static Integer[] getBoxedArray_approach2(int[] arr) {
		if (arr == null)
			return null;

		Integer[] result = Arrays.stream(arr).boxed().toArray(Integer[]::new);
		return result;
	}

	public static Integer[] getBoxedArray_approach3(int[] arr) {
		if (arr == null)
			return null;

		Integer[] result = IntStream.of(arr).boxed().toArray(Integer[]::new);
		return result;
	}

	public static void main(String args[]) throws IOException {
		int[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };

		Integer[] result1 = getBoxedArray_approach1(arr);
		printElements(result1);

		Integer[] result2 = getBoxedArray_approach2(arr);
		printElements(result2);
		
		Integer[] result3 = getBoxedArray_approach2(arr);
		printElements(result3);
	}

}

Output
1 3 5 7 2 4 6 8 10
1 3 5 7 2 4 6 8 10
1 3 5 7 2 4 6 8 10

You may like

No comments:

Post a Comment