How to convert an array of objects to an array of their primitive types in java?

Java 8Object Oriented ProgrammingProgramming

Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project.

<dependencies>
   <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.0</version>
   </dependency>
</dependencies>

This package provides a class named ArrayUtils. Using the toPrimitive() method of this class you can convert An object array to an array of primitive types:

Example

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class ArraysToPrimitives {
   public static void main(String args[]) {
      Integer[] myArray = {234, 76, 890, 27, 10, 63};
      int[] primitiveArray = ArrayUtils.toPrimitive(myArray);
      System.out.println(Arrays.toString(primitiveArray));
   }
}

Output

[234, 76, 890, 27, 10, 63]
raja
Published on 09-Jan-2018 12:56:30
Advertisements