數組與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