Saturday, 4 January 2020

How to convert double[] to Double[] in Java?


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

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

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

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

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.stream.DoubleStream;

public class App {

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

 public static Double[] getBoxedArray_approach1(double[] arr) {
  if (arr == null)
   return null;

  Double[] result = new Double[arr.length];
  int index = 0;
  for (double i : arr) {
   result[index] = Double.valueOf(i);
   index++;
  }
  return result;
 }
 
 public static Double[] getBoxedArray_approach2(double[] arr) {
  if (arr == null)
   return null;

  Double[] result = Arrays.stream(arr).boxed().toArray(Double[]::new);
  return result;
 }
 
 public static Double[] getBoxedArray_approach3(double[] arr) {
  if (arr == null)
   return null;

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

 public static void main(String args[]) {
  double[] arr = { 1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6, 8.8, 10.10 };

  Double[] result1 = getBoxedArray_approach1(arr);
  Double[] result2 = getBoxedArray_approach2(arr);
  Double[] result3 = getBoxedArray_approach3(arr);

  printElements(result1);
  printElements(result2);
  printElements(result3);

 }

}

Output
1.1 3.3 5.5 7.7 2.2 4.4 6.6 8.8 10.1
1.1 3.3 5.5 7.7 2.2 4.4 6.6 8.8 10.1
1.1 3.3 5.5 7.7 2.2 4.4 6.6 8.8 10.1



You may like

No comments:

Post a Comment