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

如果觉得JSRUN的教程对您有用,请随意打赏。您的支持将鼓励JSRUN继续提供更好的服务

捐助JSRUN
JSRUN前端教程共编系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的本前端教程,让知识的积累变得统一完整、自成体系。 希望广大工程师能一起参与进共编,让零散在世界各处的知识点找到组织、找到家。
X
支付宝
9.99
请使用支付宝扫码支付, 有效时间 5分0秒
超过有效时间后请立即停止支付。
支付故障请联系QQ:565830900
因10.00元通道已占用,系统建议您支付9.99元
正在生成二维码, 此过程可能需要15秒钟
谢谢支持,我一定会更加努力的