Java中List与数组之间的相互转换
作者:开发小鸽 发布时间:2023-09-10 03:44:28
一、前言
在Java编码中,我们经常会遇到List与数组的转换,包括对象List与对象数组的转换,以及对象List与基本数据类型数组的转换,下面详细介绍多种转换方式。
二、List列表与对象数组
List列表中存储对象,如List<Integer>
、List<String>
、List<Person>
,对象数组中同样存储相应的对象,如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()]);
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);
这个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.
*
* <p>This is a <a href="package-summary.html#StreamOps" rel="external nofollow" >terminal
* operation</a>.
*
* @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:
* <pre>{@code
* Person[] men = people.stream()
* .filter(p -> p.getGender() == MALE)
* .toArray(Person[]::new);
* }</pre>
*
* @param <A> 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);
该方法传入一个函数式接口,该接口对应一个方法引用,作用是创建一个新的指定类型和长度的数组,因此我们传入的参数就是一个Integer[]数组的构造方法的方法引用,最终得到的也就是一个Integer[]数组。
3、for循环
过于简单,不再赘述。
(二)、对象数组转对象List
1、使用Arrays.asList()
该方法通过传入一个对象数组,最后转换为一个对象List,如下所示:
Integer[] integersArray = {1, 2, 3};
// 1、使用Arrays.asList()
List<Integer> integersList = Arrays.asList(integersArray);
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}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
* </pre>
*
* @param <T> 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);
}
2、使用Collections.addAll()
通过Collections集合类的static方法将一个对象数组转换为对象List,注意首先要创建出一个对象List,使用方式如下所示:
Integer[] integersArray = {1, 2, 3};
// 2、使用Collections.addAll()
ArrayList<Integer> integersList2 = new ArrayList<>();
Collections.addAll(integersList2,integersArray);
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());
4、for循环
过于简单,不再赘述。
三、List列表与基本数据类型数组
上面我们介绍了对象List列表与对象数组之间的转换,但是有些情况需要直接将对象List转换为基本数据类型数组,如List<Integer>
转int[]
这种情况,下面详细介绍。
(一)、对象List转基本数据类型数组
1、Stream流执行转换
通过Stream流执行转换,如List<Integer>
转换为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();
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());
2、for循环
for循环是最简单、好用的方式,不再赘述。
注意,二维数组中的 list.toArray(array) 方法不能用于一维的 int[] 中。
因为 toArray() 方法的参数是范型对象,而 int 是标准数据类型。可以用 Interger[]来实现
来源:https://blog.csdn.net/Mrwxxxx/article/details/127834942


猜你喜欢
- 前言Android 自定义 View 技能是成为高级工程师所必备的,笔者觉得自定义 View 没有什么捷径可走,唯有经常练习才能解决产品需求
- 本文将引导您完成 2 个示例,演示如何在 Flutter 中获取设备标识符使用 platform_device_id如果您只需要运行应用程序
- 对象的初始化和清理生活中我们买的电子产品都基本会有出厂设置,在某一天我们不用时候也会删除一些自己信息数据保证安全。C++中的面向对象来源于生
- 一、前言SQLite是一个轻量级的、跨平台的、开源的嵌入式数据库引擎,也是一个关系型的的使用SQL语句的数据库引擎,读写效率高、资源消耗总量
- 前言前段时间看到一道面试题:“main函数可以被重载么?”,当时就蒙圈了,怎么还会有这种面试题,现在
- Monkey 是Android SDK提供的一个命令行工具, 可以简单,方便地运行在任何版本的Android模拟器和实体设备上。 Monke
- 引言Random类是非常值得学习的一个类,所以我们今天一起学习一下Random这个类,对于模拟数据这个是随机类可是一个好东西,我们可以用这个
- mybatis in查询条件过长的解决方法1:分次查询,将参数且分割成多个短的查询后合并代码: in
- 面向接口编程接口的定义及功能这里从java介入吧,在java中,接口是一种特殊的类,接口里面的量都是常量,接口的方法只有定义而没有实现,换句
- 1使用背景在实际项目中其中一部分逻辑可能会因为调用了外部服务或者等待锁等情况下出现不可预料的异常,在这个时候我们可能需要对调用这部分逻辑进行
- 猜数字游戏你在和朋友一起玩 猜数字(Bulls and Cows)游戏,该游戏规则如下:写出一个秘密数字,并请朋友猜这个数字是多少。朋友每猜
- 利用redis进行springSession的存储:存储:// 在session中保存用户信息 H
- 安卓自定义分段式的进度条,供大家参考,具体内容如下前一段时间公司新项目接到一个新需求,其中界面需要用到一个分段式的进度条,找了半天没有发现类
- 引言 基于生成图片实现了一个手机号转图片的需求。 内容也很简单,直接
- 本文实例为大家分享了C#类的多态性,供大家参考,具体内容如下第一种:编译时的多态性,直接这样说不知道说啥?程序执行过程主要分为三步:编译,链
- 学习过java基础,最近趁着大量课余时间想学习Android开发。百度很多资料Android studio,由Google开发的开发工具,那
- 在使用springmvc的时候,后台@RequestBody接受的是一个json格式的字符串,一定是一个字符串。我们可以通过@Request
- 应用情景:很多标准的方法都是利用Object.Equals方法来做对比的,例如LIst.Remove假设 某些情景下我们希望引用类型判断&a
- 使用Palette API选择颜色 良好的视觉设计是app成功所必不可少的, 而色彩设计体系是设计的基础构成. Palette包是
- 简介MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)