数组与list的转换

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

int[] arr 数组转 list

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

String[] strs 转 list

  List<String> listRes = Arrays.asList(strs);

Integer[] 转List

  List<Integer> listRes = Arrays.asList(integerRes);

 

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

List<Integer> 转 Integer[]

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

List<String> 转 String[] 

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

List<Integer> 转 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<Integer>

------------------------------------------------------------------------------------------

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

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

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

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

 

 

posted @ 2021-05-12 09:35  白玉神驹  阅读(2781)  评论(0编辑  收藏  举报