zoukankan      html  css  js  c++  java
  • Java – How to convert a primitive Array to List

    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]

    from:http://www.mkyong.com/java/java-how-to-convert-a-primitive-array-to-list/

  • 相关阅读:
    javascript,函数声明和函数表达式
    javascript,小数值舍入操作方法:ceil()、floor()、round()
    javascript,子字符串操作方法:Slice()、Substr()、Substring()的区别
    javascript,第一个基于node.js的Http服务
    javascript,创建对象的3种方法
    MFC学习笔记2——MFC和Win32
    Qt下 QString转char*
    [转载] Qt程序在Windows下的mingw发布
    VC 获取当前时间
    MFC 对话框设计问题(控件的使用)
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/10092964.html
Copyright © 2011-2022 走看看