集合數組相互轉換:int[]轉List

集合與數組的相互轉換,這裏主要介紹int[] 如何轉換成Integer[] 和 List<Integer> ,主要是有一個裝箱的過程,我們可以利用jdk8中stream用法中的boxed可以幫我們自動做裝箱操作:

package com.lsqingfeng.action.knowledge.collection;

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

/**
 * 數組與集合的相互轉換
 */
public class ListArrayDemo {
    public static void main(String[] args) {
        int []arr = {1,2,3,4,5,6};
        // int[] 轉List  boxed: 裝箱:將基本類型轉成包裝類
        List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
        System.out.println(list);

        // int[] 轉 integer[]
        Integer[] arr2 = Arrays.stream(arr).boxed().toArray(Integer[]::new);

        //List<> 轉  Integer[]
        Integer[] arr3 = list.toArray(new Integer[0]);

        // List<> 轉 int[]
        int[] arr4 = list.stream().mapToInt(Integer::intValue).toArray();

        //Integer[] 轉 int[]
        int[]arr5 = Arrays.stream(arr3).mapToInt(Integer::intValue).toArray();

        // Integer[] 轉 List<Integer>
        List<Integer> list2 = Arrays.asList(arr2);

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章