By unknown


2009-06-06 20:20:18 8 Comments

This is similar to this question: How to convert int[] to Integer[] in Java?

I'm new to Java. How can i convert a List<Integer> to int[] in Java? I'm confused because List.toArray() actually returns an Object[], which can be cast to nether Integer[] or int[].

Right now I'm using a loop to do so:

int[] toIntArray(List<Integer> list){
  int[] ret = new int[list.size()];
  for(int i = 0;i < ret.length;i++)
    ret[i] = list.get(i);
  return ret;
}

I'm sure there's a better way to do this.

16 comments

@Pumphouse 2016-09-09 04:30:02

Java 8 has given us an easy way to do this via streams...

Using the collections stream() function and then mapping to ints, you'll get an IntStream. With the IntStream we can call toArray() which gives us int []

int [] ints = list.stream().mapToInt(Integer::intValue).toArray();

to int []

to IntStream

@Mike 2009-06-08 14:55:47

int[] toIntArray(List<Integer> list)  {
    int[] ret = new int[list.size()];
    int i = 0;
    for (Integer e : list)  
        ret[i++] = e;
    return ret;
}

Slight change to your code to avoid expensive list indexing (since a List is not necessarily an ArrayList, but could be a linked list, for which random access is expensive)

@Hugh Perkins 2010-07-04 01:26:42

I dont understand: looking up an elepment in an array is not slow. It runs in O, where n is the size of the array, ie it's not dependent on the size of the array at all or anything. In C: myarray[c] is the same as: myarray + c * sizeof( myarray[0] ) ... which runs very fast.

@Arjan 2010-07-04 22:03:42

The method takes List as argument, not all implementations have fast random access (like ArrayList)

@Lajnold 2010-07-04 22:06:50

@Hugh: The difference is not how the array is accessed, but how the List is accessed. list.get(i) performs bounds checks and stuff for each access. I don't know whether the new solution is actually better, but Mike says so at least, so perhaps it is. Edit: I forgot that Java allows indexing into a linked list (I'm used to C++'s std::list, which does not allow it). So what arjantop said about non-ArrayList is true as well; indexing isn't necessarily fast even without the bounds checks.

@maaartinus 2015-04-25 17:57:37

@Lajnold The bounds checks for an ArrayList are free in a modern JIT. However, I'd prefer if Java more followed STL and implemented only methods which really make sense (LinkedList::get(int) does not as it may be arbitrary slow).

@Nearoo 2018-04-13 17:15:42

@maaartinus The entire purpose of interfaces is to separate implementation from interface. It makes perfect sense the way it is solved in Java if you understand the underlying idea. Here is some information about it.

@maaartinus 2018-04-13 20:10:44

@Nearoo No, it's a BS. The fact that you want to separate implementation from interface doesn't give you the freedom to spoil the interface, e.g., by lack of timing guarantees for most important operations. Luckily, hardly anybody uses LinkedList, so assuming List::get(int) to be a constant time operation is rather safe.

@Nearoo 2018-04-13 22:17:31

The List-interface is a so called "abstract data type". It's created without an implementation in mind. There are many different datatypes for different purposes, and many implementations with different performances. ArrayList adds a new element in O(n), and has lookup O(1). Linked list has it vice versa. Why would you restrict interfaces to only one? If you only want to support a specific runtime, you could just write "ArrayList" as a parameter type. Otherwise, the runtime can be noted in a comment. It is up to the coient to use or not use a method, it's not the responsibility of the class.

@Nearoo 2018-04-13 22:50:17

@maaartinus If a method or class doesn't guarantee a certain property in the documentation, the client musn't expect that property. You can't just go around using methods and expect them to be implemented in a "fast" way.It's not a programmers responsibility to create fast methods for you. His responsibility is to keep to his promises. In case of lists, no promises concerning efficiency is given. That's the core of the idea of interaces by the way.

@NimChimpsky 2012-11-09 16:08:05

Using a lambda you could do this (compiles in jdk lambda):

public static void main(String ars[]) {
        TransformService transformService = (inputs) -> {
            int[] ints = new int[inputs.size()];
            int i = 0;
            for (Integer element : inputs) {
                ints[ i++ ] = element;
            }
            return ints;
        };

        List<Integer> inputs = new ArrayList<Integer>(5) { {add(10); add(10);} };

        int[] results = transformService.transform(inputs);
    }

    public interface TransformService {
        int[] transform(List<Integer> inputs);
    }

@Loduwijk 2013-07-23 15:43:48

You could not have done that when the question was asked, but this is a good way to handle the situation now (assuming you have upgraded Java). What you have done could be further modified to provide a general way to transform lots of things with the same methodology. +1

@AndrewF 2018-02-13 00:45:39

The solution here is only in the loop code. The rest (functional interface, lambda, main method, list with dummy data) is extraneous and doesn't help answer the question.

@THANN Phearum 2016-10-31 08:04:25

This simple loop is always correct! no bugs

  int[] integers = new int[myList.size()];
  for (int i = 0; i < integers.length; i++) {
      integers[i] = myList.get(i);
  }

@AndrewF 2018-02-13 00:30:33

"Valid" is not the same as "ideal", and performance problems can be considered bugs. List#get(int) is not guaranteed to be a constant-time operation, as you may have assumed, so it shouldn't be used for iteration. Instead, use an iterator, which is designed for this use case. Either use the Java 5+ foreach loop or call List#iterator() and work with the iterator. Also, the list's size could change during this loop, leading to either an IndexOutOfBoundsException or an incomplete array. Many iterator implementations have well-documented strategies to handle this situation.

@Noor Nawaz 2016-07-11 10:38:14

Here is Java 8 single line code for this

public int[] toIntArray(List<Integer> intList){
       return intList.stream().mapToInt(Integer::intValue).toArray();
}

@ColinD 2010-07-04 21:32:34

In addition to Commons Lang, you can do this with Guava's method Ints.toArray(Collection<Integer> collection):

List<Integer> list = ...
int[] ints = Ints.toArray(list);

This saves you having to do the intermediate array conversion that the Commons Lang equivalent requires yourself.

@kamczak 2014-02-25 12:05:04

Unfortunately, the intermediate array is hidden inside Guava: Object[] boxedArray = collection.toArray();

@Eddified 2016-08-05 21:03:32

"Fortunately, the intermediate array is hidden inside Guava." - Fixed that for you. ;)

@Pshemo 2014-05-30 00:05:17

No one mentioned yet streams added in Java 8 so here it goes:

int[] array = list.stream().mapToInt(i->i).toArray();

Thought process:

  • simple Stream#toArray returns Object[], so it is not what we want. Also Stream#toArray(IntFunction<A[]> generator) doesn't do what we want because generic type A can't represent primitive int
  • so it would be nice to have some stream which could handle primitive type int, because its toArray method will most probably also return int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural here). And fortunately Java 8 has such stream: IntStream
  • so now only thing we need to figure out is how to convert our Stream<Integer> (which will be returned from list.stream()) to that shiny IntStream. Here mapToInt method comes to rescue. All we need to do is provide some mapping from Integer to int. We could use something like Integer#getValue which returns int:

    mapToInt( (Integer i) -> i.intValue())

    (or if someone prefers mapToInt(Integer::intValue) )

    but similar code can be generated using unboxing, since compiler knows that result of this lambda must be int (lambda in mapToInt is implementation of ToIntFunction interface which expects body for int applyAsInt(T value) method which is expected to return int).

    So we can simply write

    mapToInt((Integer i)->i)

    or simpler (since Integer i type can be inferred by compiler because List<Integer>#stream() returns Stream<Integer>)

    mapToInt(i -> i)

@Pimp Trizkit 2015-11-26 14:53:38

Clearly the best solution. Too bad it lacks explanation.

@Pshemo 2015-11-26 15:32:44

@PimpTrizkit Updated this answer a little. Hope it is clearer now.

@Pimp Trizkit 2015-11-27 03:29:46

@Pshemo - Thanks! I didn't personally need an explanation. But I hate seeing the perfect answer without one! Regardless, your explanation did educate me and was helpful. I wonder why the mapTo... functions don't allow for null lambda.... like sort does.... which makes it default to a default behavior... in this case, i -> i would be a perfect default behavior.

@vefthym 2017-03-02 10:47:34

I guess this answer is faster than ColinD's answer using Guava, right?

@Pshemo 2017-03-02 15:55:59

@vefthym I didn't test it, but I suspect that both solution work on same simple principle so I would expect similar speed (but feel free to benchmark it). One advantage of this answer is that it doesn't require additional libraries as long as we have Java 8.

@Donald Raab 2016-02-29 22:56:54

With Eclipse Collections, you can do the following if you have a list of type java.util.List<Integer>:

List<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = LazyIterate.adapt(integers).collectInt(i -> i).toArray();

Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);

If you already have an Eclipse Collections type like MutableList, you can do the following:

MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = integers.asLazy().collectInt(i -> i).toArray();

Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);

Note: I am a committer for Eclipse Collections

@Mr. Polywhirl 2015-11-30 12:54:40

If you are simply mapping an Integer to an int then you should consider using parallelism, since your mapping logic does not rely on any variables outside its scope.

int[] arr = list.parallelStream().mapToInt(Integer::intValue).toArray();

Just be aware of this

Note that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. While aggregate operations enable you to more easily implement parallelism, it is still your responsibility to determine if your application is suitable for parallelism.


There are two ways to map Integers to their primitive form:

  1. Via a ToIntFunction.

    mapToInt(Integer::intValue)
    
  2. Via explicit unboxing with lambda expression.

    mapToInt(i -> i.intValue())
    
  3. Via implicit (auto-) unboxing with lambda expression.

    mapToInt(i -> i)
    

Given a list with a null value

List<Integer> list = Arrays.asList(1, 2, null, 4, 5);

Here are three options to handle null:

  1. Filter out the null values before mapping.

    int[] arr = list.parallelStream().filter(Objects::nonNull).mapToInt(Integer::intValue).toArray();
    
  2. Map the null values to a default value.

    int[] arr = list.parallelStream().map(i -> i == null ? -1 : i).mapToInt(Integer::intValue).toArray();
    
  3. Handle null inside the lambda expression.

    int[] arr = list.parallelStream().mapToInt(i -> i == null ? -1 : i.intValue()).toArray();
    

@AndrewF 2018-02-13 00:38:47

Note that mapToInt(Integer::intValue) and mapToInt(i -> i.intValue()) are strictly identical (two ways of expressing the exact same method call), and all three are effectively identical (same bytecode).

@Loduwijk 2013-07-23 15:57:09

I'll throw one more in here. I've noticed several uses of for loops, but you don't even need anything inside the loop. I mention this only because the original question was trying to find less verbose code.

int[] toArray(List<Integer> list) {
    int[] ret = new int[ list.size() ];
    int i = 0;
    for( Iterator<Integer> it = list.iterator(); 
         it.hasNext(); 
         ret[i++] = it.next() );
    return ret;
}

If Java allowed multiple declarations in a for loop the way C++ does, we could go a step further and do for(int i = 0, Iterator it...

In the end though (this part is just my opinion), if you are going to have a helping function or method to do something for you, just set it up and forget about it. It can be a one-liner or ten; if you'll never look at it again you won't know the difference.

@gerardw 2012-02-27 19:18:45

int[] ret = new int[list.size()];       
Iterator<Integer> iter = list.iterator();
for (int i=0; iter.hasNext(); i++) {       
    ret[i] = iter.next();                
}                                        
return ret;                              

@Eddie 2009-06-06 20:48:28

The easiest way to do this is to make use of Apache Commons Lang. It has a handy ArrayUtils class that can do what you want. Use the toPrimitive method with the overload for an array of Integers.

List<Integer> myList;
 ... assign and fill the list
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));

This way you don't reinvent the wheel. Commons Lang has a great many useful things that Java left out. Above, I chose to create an Integer list of the right size. You can also use a 0-length static Integer array and let Java allocate an array of the right size:

static final Integer[] NO_INTS = new Integer[0];
   ....
int[] intArray2 = ArrayUtils.toPrimitive(myList.toArray(NO_INTS));

@Mark Byers 2012-11-29 09:35:21

The toPrimitive link is broken.

@user424174 2013-03-13 16:10:31

Here's a link to 2.6 Commons Lang API: toPrimitive

@atanamir 2013-05-24 02:56:36

Note that this will entail 2 allocations and copies: myList.toArray() will create an Integer[] and populate it, while ArrayUtils.toPrimitive() will allocate an int[] and unbox the input.

@DennisTemper 2011-06-09 10:03:56

I would recommend you to use List<?> skeletal implementation from the java collections API, it appears to be quite helpful in this particular case:

package mypackage;

import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {

//Helper method to convert int arrays into Lists
static List<Integer> intArrayAsList(final int[] a) {
    if(a == null)
        throw new NullPointerException();
    return new AbstractList<Integer>() {

        @Override
        public Integer get(int i) {
            return a[i];//autoboxing
        }
        @Override
        public Integer set(int i, Integer val) {
            final int old = a[i];
            a[i] = val;//auto-unboxing
            return old;//autoboxing
        }
        @Override
        public int size() {
            return a.length;
        }
    };
}

public static void main(final String[] args) {
    int[] a = {1, 2, 3, 4, 5};
    Collections.reverse(intArrayAsList(a));
    System.out.println(Arrays.toString(a));
}
}

Beware of boxing/unboxing drawbacks

@John Velonis 2014-03-06 22:16:07

This doesn't answer the OP's question -- the OP asked how to convert from a List to an array.

@dfa 2010-07-05 14:40:20

try also Dollar (check this revision):

import static com.humaorie.dollar.Dollar.*
...

List<Integer> source = ...;
int[] ints = $(source).convert().toIntArray();

@neesh 2009-06-06 20:33:27

There is really no way of "one-lining" what you are trying to do because toArray returns an Object[] and you cannot cast from Object[] to int[] or Integer[] to int[]

@Jon Skeet 2009-06-06 20:35:23

You can cast between Object[] and Integer[] due to array covariance - but you can't cast between int[] and Integer[].

@neesh 2009-06-06 20:38:49

thanks for correcting me I will edit my answer to reflect what you said.

@Jon Skeet 2009-06-06 20:28:18

Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:

  • List<T>.toArray won't work because there's no conversion from Integer to int
  • You can't use int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery).

I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(

Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).

@ron 2011-06-16 12:34:21

Also see ColinD's answer about guava's Ints.toArray(Collection<Integer>)

@Simon Forsberg 2013-05-24 20:30:47

@JonSkeet you mean like the horrible overloads that exists already in the Arrays class for binarySearch, copyOf, copyOfRange...? I wonder why they couldn't add another set of horrible overloads.

@Tomáลก Zato 2015-03-06 19:47:18

@ron ColinD's answer doesn't give anything but what the OP already had - for loop to fill primitive array with non-primitive one.

@Gubatron 2016-02-17 20:41:38

meanwhile at Oracle java engineers are fixated with overcomplicating the language with modules...

@Jon Skeet 2016-06-20 13:50:44

@bvdb: I'm saying that without other libraries (which basically still have the loop, but in their code not yours), I don't believe there's a better approach. That's a significantly stronger assertion than saying I don't know whether or not there is a better approach.

@MasterJoe2 2018-09-25 01:00:23

...and you can't avoid primitives until Java language designers improve it - stackoverflow.com/questions/14477743/…

Related Questions

Sponsored Content

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5780928 View
  • 7209 Score
  • 79 Answer
  • Tags:   javascript arrays

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

80 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

23 Answered Questions

[SOLVED] How do I declare and initialize an array in Java?

  • 2009-07-29 14:22:27
  • bestattendance
  • 4190155 View
  • 1864 Score
  • 23 Answer
  • Tags:   java arrays declare

39 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

64 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3806835 View
  • 3238 Score
  • 64 Answer
  • Tags:   java random integer

31 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

44 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

25 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1806213 View
  • 2108 Score
  • 25 Answer
  • Tags:   java arrays

12 Answered Questions

[SOLVED] How to convert int[] to Integer[] in Java?

Sponsored Content