数组与list的转换

数组与list的转换,第1张

数组与list的转换

数组转list 常用分为int[]类型,String[]类型和Integer[]类型

int[] arr 数组转 list

List listRes = Arrays.stream(arr).boxed().collect(Collectors.toList());

String[] strs 转 list

List listRes = Arrays.asList(strs);

Integer[] 转List

List listRes = Arrays.asList(integerRes);

list 转数组 常用分为 转int[], 转 Integer[], 转 String[]

List 转 Integer[]

Integer[] integerRes = list.toArray(new Integer[list.size()]);

List 转 String[]

String[] strRes= list.toArray(new String[0]);

List 转 int[]

int[] arrRes = list.stream().mapToInt(Integer::valueOf).toArray();


数组间的互转

int[] arr转 Integer[]

Integer[] integerRes = Arrays.stream(arr).boxed().toArray(Integer[]::new);

Integer[] 转 int[]

int[] arrRes = Arrays.stream(integerRes).mapToInt(Integer::valueOf).toArray();

String[] 转 int[]

int[] arrRes = Arrays.asList(strRes).stream().mapToInt(Integer::parseInt).toArray();

或 Arrays.stream(strRes).mapToInt(Integer::parseInt).toArray();


mapToInt(Integer::valueOf)将对象流转为基本类型流

toArray()转为为int数组

Arrays.stream(arr)转为流 将int数组转化为IntStream

boxed()装箱,将基本类型流转换为对象流

toArray(Integer::new)将对象流转换为对象数组

collect(Collectors.toList())将对象流收集为集合,转为List


Arrays.stream(arr) 可以替换成IntStream.of(arr)。

1.使用Arrays.stream将int[]转换成IntStream。

2.使用IntStream中的boxed()装箱。将IntStream转换成Stream。

3.使用Stream的collect(),将Stream转换成List,因此正是List。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5722162.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存