Approach
1: By traversing to the elements of array
public static List<Long> getBoxedList_approach1(long[] arr) {
if (arr == null)
return null;
List<Long> result = new ArrayList<>();
for (long i : arr) {
result.add(i);
}
return result;
}
Approach
2: Using LongStream
public static List<Long> getBoxedList_approach2(long[] arr) {
if (arr == null)
return null;
List<Long> result = LongStream.of(arr).boxed().collect(Collectors.toList());
return result;
}
Approach
3: Using Arrays.stream
public static List<Long> getBoxedList_approach3(long[] arr) {
if (arr == null)
return null;
List<Long> result = Arrays.stream(arr).boxed().collect(Collectors.toList());
return result;
}
App.java
package com.sample.app;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
public class App {
private static void printElements(List<Long> arr) {
for (long i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static List<Long> getBoxedList_approach1(long[] arr) {
if (arr == null)
return null;
List<Long> result = new ArrayList<>();
for (long i : arr) {
result.add(i);
}
return result;
}
public static List<Long> getBoxedList_approach2(long[] arr) {
if (arr == null)
return null;
List<Long> result = LongStream.of(arr).boxed().collect(Collectors.toList());
return result;
}
public static List<Long> getBoxedList_approach3(long[] arr) {
if (arr == null)
return null;
List<Long> result = Arrays.stream(arr).boxed().collect(Collectors.toList());
return result;
}
public static void main(String args[]) throws IOException {
long[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
List<Long> result1 = getBoxedList_approach1(arr);
printElements(result1);
List<Long> result2 = getBoxedList_approach2(arr);
printElements(result2);
List<Long> result3 = getBoxedList_approach3(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