首页 > 其他分享 >原生数组转包装类(基本类型数组、包装类数组、集合之间的相互转换(以及遍历方法))

原生数组转包装类(基本类型数组、包装类数组、集合之间的相互转换(以及遍历方法))

时间:2022-10-25 13:22:19浏览次数:54  
标签:原生 遍历 包装 List int 数组 Integer printElement

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Arrays.*;

public class ZhuanHuan{
    public static void main(String[] args) {
        //数组: int[]
        int[] arrayInt = new int[]{1,2,3,4,5,6};
        printElement(arrayInt);

        //原生数组转包装类数组: int[] 2 Integer[]
        Integer[] arrayInter = Arrays.stream(arrayInt).boxed().toArray(Integer[]::new);
        printElement(arrayInter);

        //*包装类数组转List/ArrayList: Integer[] 2 List<Integer>
        List<Integer> listInter = Arrays.asList(arrayInter);
        printElement(listInter);

        //*List/ArrayList转包装类数组: List<Integer> 2 Integer[]
        Integer[] arrayInter2 = listInter.toArray(new Integer[listInter.size()]);
        printElement(arrayInter2);

        //包装类数组转原生数组: Integer[] 2 int[]
        int[] arrayInt2 = Arrays.stream(arrayInter2).mapToInt(Integer::valueOf).toArray();
        printElement(arrayInt2);

        //原生数组转List/ArrayList: int[] 2 List<Integer>
        List<Integer> listInter2 = Arrays.stream(arrayInt2).boxed().collect(Collectors.toList());
        printElement(listInter2);

        //List/ArrayList转原生数组: List<Integer> 2 int[]
        int[] arrayInt3 = listInter2.stream().mapToInt(Integer::valueOf).toArray();
        printElement(arrayInt3);

    }
    //原生数组遍历输出
    private static void printElement(int[] arr){
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
    //包装类数组遍历输出
    private static void printElement(Integer[] arr){
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
    //List遍历输出
    private static void printElement(List list){
        Iterator iter = list.iterator();
        while(iter.hasNext()){
            System.out.println(iter.next());
        }
    }
}

标签:原生,遍历,包装,List,int,数组,Integer,printElement
From: https://www.cnblogs.com/rosetta/p/16824545.html

相关文章