Java中List, Integer[], int[]的相互轉換

有時候list<Integer>和數組int[]轉換很麻煩。

List<String>和String[]也同理。難道每次非得寫一個循環遍歷嗎?其實一步就可以搞定。

本文涉及到一些Java8的特性。如果沒有接觸過就先學會怎麼用,然後再細細研究。

 

package rainsheep;

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

public class Main {
    public static void main(String[] args) {
        int[] arr={1,2,3,4,5};

        // int[] 轉 List<Integer>
        List<Integer> arr1 = Arrays.stream(arr).boxed().collect(Collectors.toList());
        //1.調用Arrays.stream()將int[]變爲IntStream流,注意不能用Stream.of(),Stream.of()只適用於對象數組
        //2.使用IntStream中的boxed()裝箱。將IntStream轉換成Stream<Integer>。
        //3.使用Stream的collect(),將Stream<T>轉換成List<T>,因此正是List<Integer>。

        // int[] 轉 Integer[]
        Integer[] arr2 = Arrays.stream(arr).boxed().toArray(Integer[]::new);
        // 1.前兩步同上,此時是Stream<Integer>。
        // 2.然後使用Stream的toArray,引用Integer[]的new方法。
        // 3.這樣就可以返回Integer數組,不然默認是Object[]。

        // List<Integer> 轉 Integer[]
        Integer[] arr3 = arr1.toArray(new Integer[0]);
        // 1. 調用toArray。傳入參數T[] a。這種用法是目前推薦的。
        // List<String>轉String[]也同理。

        // List<Integer> 轉 int[]
        int[] arr4 = arr1.stream().mapToInt(Integer::valueOf).toArray();
        // 1.想要轉換成int[]類型,就得先轉成IntStream。
        // 2.這裏就通過mapToInt()把Stream<Integer>調用Integer::valueOf來轉成IntStream
        // 3.而IntStream中默認toArray()轉成int[]。


        // Integer[] 轉 int[]
        int[] arr5 = Stream.of(arr2).mapToInt(Integer::valueOf).toArray();
        // 思路同上。先將Integer[]轉成Stream<Integer>,再轉成IntStream。

        // Integer[] 轉 List<Integer>
        List<Integer> arr6 = Arrays.asList(arr2);
        // 最簡單的方式。String[]轉List<String>也同理。
        
    }
}

 

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