Home » Core Java » Java 8 Convert a primitive Array to List Example

About Mohammad Meraj Zia

Mohammad Meraj Zia
I did my Engineering in Information Technology from IET, Lucknow, India. Currently doing MSc in Information Technology from Derby University. I have worked in Java/J2EE domain for the last 10 years. Have good understanding of Payment and Finance domains.

Java 8 Convert a primitive Array to List Example

In this article we will learn how to Convert a primitive Array to List using Java 8. For this example we will use IDEA IntelliJ but you can also use any IDE.

1. Introduction

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Each item in an array is called an element, and each element is accessed by its numerical index.

A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods.

 
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list. The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behaviour and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as “optional” in the specification for this interface.

2. Java Collection Framework

In this section we will discuss Java Collection Framework. I think its important to discuss about it to know how the different implementation of collections works. If you are only interested to know the code you can skip this section and move to the next section.

Collection is the root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific sub-interfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.
Bags or multisets (unordered collections that may contain duplicate elements) should implement this interface directly.

All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its sub-interfaces) should provide two “standard” constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. There is no way to enforce this convention (as interfaces cannot contain constructors) but all of the general-purpose Collection implementations in the Java platform libraries comply.

The “destructive” methods contained in this interface, that is, the methods that modify the collection on which they operate, are specified to throw UnsupportedOperationException if this collection does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the collection. For example, invoking the addAll(Collection) method on an unmodifiable collection may, but is not required to, throw the exception if the collection to be added is empty.

Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behaviour and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as “optional” in the specification for this interface.

It is up to each collection to determine its own synchronization policy. In the absence of a stronger guarantee by the implementation, undefined behaviour may result from the invocation of any method on a collection that is being mutated by another thread; this includes direct invocations, passing the collection to a method that might perform invocations, and using an existing iterator to examine the collection.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object o) method says: “returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).” This specification should not be construed to imply that invoking Collection.contains with a non-null argument o will cause o.equals(e) to be invoked for any element e. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two elements. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

3. Java 8 Convert a primitive Array to List – Example

In this section we will see a working example. We will initialize a primitive array then will look at the different ways of converting it to a List.

We will look at the simplest way to achieve this. We will first create and initialize a primitive array as below:

int[] primitiveArr = new int[]{1,2, 10, 6, 788, 32};

Then we will iterate through this array using our favourite, traditional for loop and in every iteration populate the list:

List<Integer> list = new ArrayList(primitiveArr.length);
for(int i : primitiveArr) {
    list.add(Integer.valueOf(i));
}

We can use Java 8 Stream API to convert int array to list of Integer. Below are the steps:

  • Convert the primitive array to a sequential stream using Arrays.stream()
  • Box each element of the stream to an Integer using IntStream.boxed(). This returns a Stream consisting of the elements of this stream, each boxed to an Integer.
  • Use Collectors.toList() to accumulate the input elements into a new list. This method returns a Collector that accumulates the input elements into a new List. There is no guarantee on the type, mutability, serializability or thread-safety of the list returned.
List<Integer> listUsingJava8 = Arrays.stream(primitiveArr).boxed().collect(Collectors.toList());

Another way of doing the same this is to use IntStream.of():

List<Integer> listUsingIntStream = IntStream.of(primitiveArr).boxed().collect(Collectors.toList());

There is another way to achieve the above. First we convert int array to Integer array. Then we use Collections.addAll() to add all the elements of Integer array to the given list.

Integer[] boxedArray = Arrays.stream(primitiveArr).boxed().toArray(Integer[]::new);
List<Integer> list2 = new ArrayList();
Collections.addAll(list2, boxedArray);

ArrayToList.java

package com.javacodegeeks;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ArrayToList {

    public static void main(String[] args) {
        int[] primitiveArr = new int[]{1,2, 10, 6, 788, 32};

        // Before Java 8
        List<Integer> list = new ArrayList(primitiveArr.length);
        for(int i : primitiveArr) {
            list.add(Integer.valueOf(i));
        }

        System.out.println("Before Java8 > " + list);

        List<Integer> listUsingJava8 = Arrays.stream(primitiveArr).boxed().collect(Collectors.toList());
        System.out.println("Java8 > " + listUsingJava8);

        List<Integer> listUsingIntStream = IntStream.of(primitiveArr).boxed().collect(Collectors.toList());
        System.out.println("IntStream > " + listUsingIntStream);

        Integer[] boxedArray = Arrays.stream(primitiveArr).boxed().toArray(Integer[]::new);
        List<Integer> list2 = new ArrayList();
        Collections.addAll(list2, boxedArray);
        System.out.println("Another way > " + list2);
    }
}

4. Conclusion

In this article we saw different ways of converting a primitive array to a list. We saw a traditional way of using a loop to populate the list by iterating the array. The we looked at the Java * version by using streams. There are other third party libraries which you can use to achieve the same but I don’t see any reason why one would not use the standard Java version.

5. Download the Source Code

That was an example of Java 8 Convert a primitive Array to List.

Download
You can download the full source code of this example here: Array to List
(-4 rating, 4 votes)
5 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

5
Leave a Reply

avatar
3 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
rmpbklynPascalMohammad Meraj ZiaKayMilind Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Milind
Guest
Milind

Or just use Arrays.asList

Pascal
Guest
Pascal

Well, I think the author is correct using autoboxing instead of Arrays.asList as Arrays.asList won’t be able to turn a primitive array to an object list directly, e.g., List list = Arrays.asList(new int[]{1,2,3,4}) won’t work, yet List list = Arrays.stream(new int[]{1,2,3,4}).boxed().collect(Collectors.toList()) will.

Kay
Guest

A list isn’t ordered strictly. Unless you consider insertion order. Typically ordered means that there is additional logic within the collection to determine an object’s location within the array at insertion time based on it’s relationship to other objects already in the collection. If it were ordered, it wouldn’t expose sort by convention, or allow access at index, both of which it does.

rmpbklyn
Guest

wonderful, the instream worked for me :-)