Java各类数组与容器的互转

不知小伙伴们是否常常在刷题时,因为数组与容器应该如何使用函数进行转换而感到苦恼。那么这篇文章将会细数各种类型,如一维int数组、二维int数组、char数组、String数组。

一、一维int数组与List<Integer>

public class IntArrayAndIntegerList {
   

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

        //数组转List
        //一.逐个添加,基本做法
        List<Integer> numList2 = new ArrayList<>();
        for (int num : nums) {
   
            numList2.add(num);
        }

        //二.Stream流计算,推荐做法
        //1.数组转流
        //2.boxed 基本类型装箱成对象
        //3.对象数组转List集合
        List<Integer> numList1 = Arrays.stream(nums).boxed().collect(Collectors.toList());

        //List转回数组
        //一.逐个添加, 基本做法
        int[] nums1 = 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值