数组与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>。

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM