Java – How to convert a primitive Array to List

Code snippets to convert a primitive array int[] to a List<Integer> :


	int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

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

In Java 8, you can use the Stream APIs to do the boxing and conversion like this :


	List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());

1. Classic Example

Full example to convert a primitive Array to a List.

ArrayExample1.java

package com.mkyong.array;

import java.util.ArrayList;
import java.util.List;

public class ArrayExample1 {

    public static void main(String[] args) {

        int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        List<Integer> list = convertIntArrayToList(number);
        System.out.println("list : " + list);

    }

    private static List<Integer> convertIntArrayToList(int[] input) {

        List<Integer> list = new ArrayList<>();
        for (int i : input) {
            list.add(i);
        }
        return list;

    }
}

Output


list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note
You can’t use the popular Arrays.asList to convert it directly, because boxing issue.


	int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	// No, the return type is not what we want
	List<int[]> ints = Arrays.asList(number);

2. Java 8 Stream

Full Java 8 stream example to convert a primitive Array to a List.

ArrayExample2.java

package com.mkyong.array;

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

public class ArrayExample2 {

    public static void main(String[] args) {

        int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        // IntStream.of or Arrays.stream, same output
        //List<Integer> list = IntStream.of(number).boxed().collect(Collectors.toList());
		
        List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());
        System.out.println("list : " + list);

    }
}

Output


list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

References

  1. IntStream JavaDoc
  2. Java – Convert Array to Stream

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Brian L
Guest
Brian L

I’ve learnt of lots of java 8, spring boot and hibernate basic knowledge/skills from here, tks Mkyong.

anurag singh
Guest
anurag singh

Thanks for sharing this nice article about java 8 new features.
keep writing for us.