java中數組和ArrayList的互轉


java中基本類型數組[]和ArrayList之間的互相轉換在算法實現過程中經常使用。

  

 1         int[] data = {4, 5, 3, 6, 2, 5, 1};
 2  
 3         // int[] 轉 List<Integer>
 4         List<Integer> list1 = Arrays.stream(data).boxed().collect(Collectors.toList());
 5         // Arrays.stream(arr) 可以替換成IntStream.of(arr)。
 6         // 1.使用Arrays.stream將int[]轉換成IntStream。
 7         // 2.使用IntStream中的boxed()裝箱。將IntStream轉換成Stream<Integer>。
 8         // 3.使用Stream的collect(),將Stream<T>轉換成List<T>,因此正是List<Integer>。
 9  
10         // int[] 轉 Integer[]
11         Integer[] integers1 = Arrays.stream(data).boxed().toArray(Integer[]::new);
12         // 前兩步同上,此時是Stream<Integer>。
13         // 然后使用Stream的toArray,傳入IntFunction<A[]> generator。
14         // 這樣就可以返回Integer數組。
15         // 不然默認是Object[]。
16  
17         // List<Integer> 轉 Integer[]
18         Integer[] integers2 = list1.toArray(new Integer[0]);
19         //  調用toArray。傳入參數T[] a。這種用法是目前推薦的。
20         // List<String>轉String[]也同理。
21  
22         // List<Integer> 轉 int[]
23         int[] arr1 = list1.stream().mapToInt(Integer::valueOf).toArray();
24         // 想要轉換成int[]類型,就得先轉成IntStream。
25         // 這里就通過mapToInt()把Stream<Integer>調用Integer::valueOf來轉成IntStream
26         // 而IntStream中默認toArray()轉成int[]。
27  
28         // Integer[] 轉 int[]
29         int[] arr2 = Arrays.stream(integers1).mapToInt(Integer::valueOf).toArray();
30         // 思路同上。先將Integer[]轉成Stream<Integer>,再轉成IntStream。
31  
32         // Integer[] 轉 List<Integer>
33         List<Integer> list2 = Arrays.asList(integers1);
34         // 最簡單的方式。String[]轉List<String>也同理。
35  
36         // 同理
37         String[] strings1 = {"a", "b", "c"};
38         // String[] 轉 List<String>
39         List<String> list3 = Arrays.asList(strings1);
40         // List<String> 轉 String[]
41         String[] strings2 = list3.toArray(new String[0]);

 

 注意:不行的話就直接進行循環暴力操作,問題不大


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM