Java 8 Convert Primitive Array to List using Streams API

6 months ago codedestine 0

Java 8 Convert Primitive Array to List :- In this tutorial, we will learn to convert primitive array to list using Stream API.

Java 8 Convert Primitive Array to List

Converting an array of objects to a list is very easy and straightforward, you can use Arrays.asList() directly to convert it but this method does not work for converting primitive type arrays because of boxing issue. Let’s see, how to convert primitive array to list using old approach of Java 7 and new approach of using Stream API in Java 8.  

Problem Statement :-

Given an array of primitive int data type, convert it to the list of Integer objects and print all the int values.

Let’s see the implementation of above problem in java 7 and in java 8.

Java 7 :- To implement this, first create an object of Integer type ArrayList, iterate through the array of primitive int values and add it to the list of integers.

  public static void main(String args[]){
 
    int[] intArray = {1, 2, 3, 4, 5};
 
    List<Integer> list = new ArrayList<Integer>();
    for (int i : intArray) {
      list.add(i);
    }
 
    for(Integer num:list){
      System.out.println(num);
    }
  }

Java 8 :- To implement this, we will use IntStream Class of Stream API.

  public static void main(String args[]){
 
    int[] intArray = {1, 2, 3, 4, 5};

    // first :- create IntStream by calling its static Of method
    // second :- convert IntStream to stream of Integers by calling its boxed method
    List<Integer> list = IntStream.of(intArray).boxed().collect(Collectors.toList());
 
    list.forEach(System.out::println);

  }  

Result :- 

1
2
3
4
5

Reference :-  IntStream JavaDocs 

That’s all for Java 8 Convert Primitive Array to List. If you liked it, please share your thoughts in comments section and share it with others too.