Saturday 4 January 2020

How to convert double[] to List in Java?


Approach 1: By traversing to the elements of array
public static List<Double> getBoxedList_approach1(double[] arr) {
 if (arr == null)
  return null;

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

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

 }
 return result;
}


Approach 2: Using DoubleStream
public static List<Double> getBoxedList_approach2(double[] arr) {
 if (arr == null)
  return null;

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


Approach 3: Using Arrays.stream
public static List<Double> getBoxedList_approach3(double[] arr) {
 if (arr == null)
  return null;

 List<Double> 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.DoubleStream;

public class App {

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

 public static List<Double> getBoxedList_approach1(double[] arr) {
  if (arr == null)
   return null;

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

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

  }
  return result;
 }

 public static List<Double> getBoxedList_approach2(double[] arr) {
  if (arr == null)
   return null;

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

 public static List<Double> getBoxedList_approach3(double[] arr) {
  if (arr == null)
   return null;

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

 public static void main(String args[]) throws IOException {
  double[] arr = { 1.1, 3.3, 5.5, 7, 2, 4, 6, 8, 10 };

  List<Double> result1 = getBoxedList_approach1(arr);
  printElements(result1);

  List<Double> result2 = getBoxedList_approach2(arr);
  printElements(result2);

  List<Double> result3 = getBoxedList_approach3(arr);
  printElements(result3);

 }
}

Output
1.1 3.3 5.5 7.0 2.0 4.0 6.0 8.0 10.0
1.1 3.3 5.5 7.0 2.0 4.0 6.0 8.0 10.0
1.1 3.3 5.5 7.0 2.0 4.0 6.0 8.0 10.0



You may like

No comments:

Post a Comment