Friday, 3 January 2020

How to convert int[] to List in Java?


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

 List<Integer> result = new ArrayList<>();

 for (int i : arr) {
  result.add(i);

 }
 return result;
}


Approach 2: Using ‘Arrays.stream’.
List<Integer> result = Arrays.stream(arr).boxed().collect(Collectors.toList());

Approach 3: Using DoubleStream.
List<Integer> result = IntStream.of(arr).boxed().collect(Collectors.toList());


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.IntStream;

public class App {

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

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

  List<Integer> result = new ArrayList<>();

  for (int i : arr) {
   result.add(i);

  }
  return result;
 }

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

  List<Integer> result = Arrays.stream(arr).boxed().collect(Collectors.toList());
  return result;
 }

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

  List<Integer> result = IntStream.of(arr).boxed().collect(Collectors.toList());
  return result;
 }

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

  List<Integer> result1 = getBoxedArray_approach1(arr);
  printElements(result1);

  List<Integer> result2 = getBoxedArray_approach2(arr);
  printElements(result2);

  List<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