How to convert Wrapper value array list into primitive array in Java?

Java 8Object Oriented ProgrammingProgramming

Here, to convert Wrapper value array list into primitive array, we are considering Integer as Wrapper, whereas double as primitive.

At first, declare an Integer array list and add elements to it −

ArrayList < Integer > arrList = new ArrayList < Integer > ();
arrList.add(5);
arrList.add(10);
arrList.add(15);
arrList.add(20);
arrList.add(25);
arrList.add(30);
arrList.add(45);
arrList.add(50);

Now, convert the above Integer array list to primitive array. Firstly, we set the same size for the double array and then assigned each value

final double[] arr = new double[arrList.size()];
int index = 0;
for (final Integer value: arrList) {
   arr[index++] = value;
}

The following is an example to convert an Integer (wrapper) array list into a double array (primitive) −

Example

 Live Demo

import java.util.ArrayList;
public class Demo {
   public static void main(String[] args) {
      ArrayList<Integer>arrList = new ArrayList<Integer>();
      arrList.add(5);
      arrList.add(10);
      arrList.add(15);
      arrList.add(20);
      arrList.add(25);
      arrList.add(30);
      arrList.add(45);
      arrList.add(50);
      final double[] arr = new double[arrList.size()];
      int index = 0;
      for (final Integer value: arrList) {
         arr[index++] = value;
      }
      System.out.println("Elements of double array...");
      for (Double i: arr) {
         System.out.println(i);
      }
   }
}

output 

Elements of double array...
5.0
10.0
15.0
20.0
25.0
30.0
45.0
50.0
raja
Published on 23-Apr-2019 15:03:36
Advertisements