Skip to main content

How do I create a list or collection of primitive types

In this Q&A, we'll go over why and how to create a collection of primitive types in Java

Issue

Before we go into the why, let's understand the issue first.  The code below will generate a compile error
List<int> l = new ArrayList<>();

Java supports creating a collection of objects not primitives.

Why do I need to create a collection of primitives

The code below works fine.
List<Integer> l = new LinkedList<>();
for( int i =0; i < 100; ++i)
       l.add(i);

What's happening here is the int primitive is auto boxed into an Integer object.  To avoid the overhead of auto-boxing and un-boxing one needs to create a list of primitives.

What are my options

Java does not provide support for primitive collections out of the box.   One can create an IntStream object and perform operations on the stream.  

In addition, there are four known implementations of primitive collections from Trove, FastUtil, Guava and Colt

We'll go over how to use IntStream, Trove and FastUtil primitive classes.

Using Stream API

Code below does not involve any auto-conversion from int to Integer.

int[] p = { 1,2,3,4,5 };
IntStream is = IntStream.of( p );
is.forEach( x -> System.out.println( x ) );

Using Trove

To use the Trove, you've to include the following dependency.  You can create an integer array list with TIntArrayList class.

<dependency>
    <groupId>net.sf.trove4j</groupId>
    <artifactId>trove4j</artifactId>
    <version>3.0.2</version>
</dependency>

TIntArrayList ti = new TIntArrayList();
for( int i = 0; i < 1000; ++i)
    ti.add(i);
for( int i = 0; i < 1000; ++i)
    ti.set(i, i+1);

Using FastUtil

To use the FastUtil, you've to include the following dependency.  You can create an integer array list with IntArrayList class.

<dependency>
    <groupId>it.unimi.dsi</groupId>
    <artifactId>fastutil</artifactId>
    <version>8.1.0</version>
</dependency>

IntArrayList il = new IntArrayList();
for( int i = 0; i < 1000; ++i)
    il.add(i);
il.forEach((IntConsumer) System.out::println);

Comments