码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • List与数组之间的相互转换


    文章目录

      • 一、前言
      • 二、List列表与对象数组
        • (一)对象List转对象数组
          • 1、toArray()方法
          • 2、Stream流的toArray()方法
          • 3、for循环
        • (二)、对象数组转对象List
          • 1、使用Arrays.asList()
          • 2、使用Collections.addAll()
          • 3、使用Stream中的Collector
          • 4、for循环
      • 三、List列表与基本数据类型数组
        • (一)、对象List转基本数据类型数组
        • 1、Stream流执行转换
          • 2、for循环
        • (二)、基本数据类型数组转对象List
          • 1、Stream流转换
          • 2、for循环

    一、前言

      在Java编码中,我们经常会遇到List与数组的转换,包括对象List与对象数组的转换,以及对象List与基本数据类型数组的转换,下面详细介绍多种转换方式。


    二、List列表与对象数组

      List列表中存储对象,如List、List、List,对象数组中同样存储相应的对象,如Integer[]、String[]、Person[],对象数组与对象List的转换可通过如下方式实现:


    (一)对象List转对象数组

    1、toArray()方法

      直接调用对象List的toArray()方法转换为对象数组,该方法的参数是T[],因此需要传入对应的对象数组构造函数,指定数组的长度,如下所示:

    ArrayList<Integer> integersList = new ArrayList<>(Arrays.asList(1,2,3)); 
    // 1、toArray()方法
    Integer[] integersArrau = integersList.toArray(new Integer[integersList.size()]);
    
    • 1
    • 2
    • 3

    2、Stream流的toArray()方法

      通过Stream流的toArray()方法,传入参数是对应对象的构造方法的方法引用,使用方式如下所示:

    ArrayList<Integer> integersList = new ArrayList<>(Arrays.asList(1,2,3));
    // 2、Stream流的toArray()方法
    Integer[] integersArray2 = integersList.stream().toArray(Integer[]::new);
    
    • 1
    • 2
    • 3

      这个toArray()方法是Stream类下的,该方法说明如下所示:

    /**
     * Returns an array containing the elements of this stream, using the
     * provided {@code generator} function to allocate the returned array, as
     * well as any additional arrays that might be required for a partitioned
     * execution or for resizing.
     *
     * 

    This is a terminal * operation. * * @apiNote * The generator function takes an integer, which is the size of the * desired array, and produces an array of the desired size. This can be * concisely expressed with an array constructor reference: *

    {@code
     *     Person[] men = people.stream()
     *                          .filter(p -> p.getGender() == MALE)
     *                          .toArray(Person[]::new);
     * }
    * * @param the element type of the resulting array * @param generator a function which produces a new array of the desired * type and the provided length * @return an array containing the elements in this stream * @throws ArrayStoreException if the runtime type of the array returned * from the array generator is not a supertype of the runtime type of every * element in this stream */
    <A> A[] toArray(IntFunction<A[]> generator);
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

      该方法传入一个函数式接口,该接口对应一个方法引用,作用是创建一个新的指定类型和长度的数组,因此我们传入的参数就是一个Integer[]数组的构造方法的方法引用,最终得到的也就是一个Integer[]数组。


    3、for循环

      过于简单,不再赘述。


    (二)、对象数组转对象List

    1、使用Arrays.asList()

      该方法通过传入一个对象数组,最后转换为一个对象List,如下所示:

    Integer[] integersArray = {1, 2, 3};
    // 1、使用Arrays.asList()
    List<Integer> integersList = Arrays.asList(integersArray);
    
    • 1
    • 2
    • 3

      asList方法传入的参数是一个可变参数,因此既可以传入多个参数,也可以传入一个数组,如下所示:

    /**
     * Returns a fixed-size list backed by the specified array.  (Changes to
     * the returned list "write through" to the array.)  This method acts
     * as bridge between array-based and collection-based APIs, in
     * combination with {@link Collection#toArray}.  The returned list is
     * serializable and implements {@link RandomAccess}.
     *
     * 

    This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: *

     *     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
     * 
    * * @param the class of the objects in the array * @param a the array by which the list will be backed * @return a list view of the specified array */
    @SafeVarargs @SuppressWarnings("varargs") public static <T> List<T> asList(T... a) { return new ArrayList<>(a); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    2、使用Collections.addAll()

      通过Collections集合类的static方法将一个对象数组转换为对象List,注意首先要创建出一个对象List,使用方式如下所示:

    Integer[] integersArray = {1, 2, 3};
    // 2、使用Collections.addAll()
    ArrayList<Integer> integersList2 = new ArrayList<>();
    Collections.addAll(integersList2,integersArray);
    
    • 1
    • 2
    • 3
    • 4

    3、使用Stream中的Collector

      JDK8之后可以使用Stream流来执行转换操作,通过Stream流的终结操作collect来指定将要转换得到的List:

    Integer[] integersArray = {1, 2, 3};
    // 3、使用Stream中的Collector
    List<Integer> integersList3 = Arrays.stream(integersArray).collect(Collectors.toList());
    
    • 1
    • 2
    • 3

    4、for循环

      过于简单,不再赘述。


    三、List列表与基本数据类型数组

      上面我们介绍了对象List列表与对象数组之间的转换,但是有些情况需要直接将对象List转换为基本数据类型数组,如List转int[]这种情况,下面详细介绍。


    (一)、对象List转基本数据类型数组

    1、Stream流执行转换

      通过Stream流执行转换,如List转换为int[],通过Stream流的mapToInt()可将每个Integer转换为int,再输出为int数组,如下所示:

    ArrayList<Integer> integersList = new ArrayList<>(Arrays.asList(1,2,3));
    // 1、Stream流执行转换
    // 方法引用
    int[] arrays1 = integersList.stream().mapToInt(Integer::intValue).toArray();
    // lambda表达式
    int[] arrays2 = integersList.stream().mapToInt(i -> i).toArray();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2、for循环

      过于简单,不再赘述。


    (二)、基本数据类型数组转对象List

    1、Stream流转换

      以int[]数组来举例,通过Stream流的mapToObj()方法先将int[]数组中每个int值转换为Integer包装类,再通过collect执行终结操作转换为Integer的List。

    int[] integersArray = {1, 2, 3};
    // 1、Stream流转换
    List<Integer> integersList = Arrays.stream(integersArray).mapToObj(Integer::new).collect(Collectors.toList());
    
    • 1
    • 2
    • 3

    2、for循环

      for循环是最简单、好用的方式,不再赘述。

  • 相关阅读:
    【2023_10_22计算机热点知识分享】:人工智能
    有哪些视频媒体?邀请视频媒体报道活动的好处
    借助 ZooKeeper 生成唯一 UUID
    龙口联合化学通过注册:年营收5.5亿 李秀梅控制92.5%股权
    2.zigbee开发,zigbee点亮灯,如何正确使用别人提供的模板文件
    vue项目部署,出现两个ip的原因
    抗疫逆行者HTML网页作业 感动人物网页代码成品 最美逆行者网页模板 致敬疫情感动人物网页设计制作
    现代 CSS 之高阶图片渐隐消失术
    week9|查阅文章 Mac os M2芯片 arm64架构|安装paddlepaddle问题
    Unity之ShaderGraph如何实现全息投影效果
  • 原文地址:https://blog.csdn.net/Mrwxxxx/article/details/127834942
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号