Approach
1: Traversing to each
element and convert.
public static Long[] getBoxedArray_approach1(long[] arr) {
if (arr == null)
return null;
Long[] result = new Long[arr.length];
int index = 0;
for (long i : arr) {
result[index] = Long.valueOf(i);
index++;
}
return result;
}
Approach
2: Using
‘Arrays.stream’.
Long[] result
= Arrays.stream(arr).boxed().toArray(Long[]::new);
Approach
3: Using LongStream.
Long[] result
= LongStream.of(arr).boxed().toArray(Long[]::new);
package com.sample.app;
import java.util.Arrays;
import java.util.stream.LongStream;
public class App {
private static void printElements(Long[] arr) {
for (long i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static Long[] getBoxedArray_approach1(long[] arr) {
if (arr == null)
return null;
Long[] result = new Long[arr.length];
int index = 0;
for (long i : arr) {
result[index] = Long.valueOf(i);
index++;
}
return result;
}
public static Long[] getBoxedArray_approach2(long[] arr) {
if (arr == null)
return null;
Long[] result = Arrays.stream(arr).boxed().toArray(Long[]::new);
return result;
}
public static Long[] getBoxedArray_approach3(long[] arr) {
if (arr == null)
return null;
Long[] result = LongStream.of(arr).boxed().toArray(Long[]::new);
return result;
}
public static void main(String args[]) {
long[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
Long[] result1 = getBoxedArray_approach1(arr);
Long[] result2 = getBoxedArray_approach2(arr);
Long[] result3 = getBoxedArray_approach3(arr);
printElements(result1);
printElements(result2);
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