1.数组转list,常用数组分为int[]类型,String[]类型和Integer[]类型
int[] arr 数组转 list
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
String[] strs 转 list
List<String> list2 = Arrays.asList(arr2);
Integer[] 转List
List<Integer> list3 = Arrays.asList(arr3);
2.list 转数组 常用数组分为 转int[], 转 Integer[], 转 String[]
List 转 Integer[]
Integer[] integers = list.toArray(new Integer[list.size()]);
List 转 String[]
String[] strings = list2.toArray(new String[0]);
List 转 int[]
int[] ints = list3.stream().mapToInt(Integer::valueOf).toArray();
3.数组间的互转
int[] arr转 Integer[]
Integer[] integers = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Integer[] 转 int[]
int[] ints = Arrays.stream(arr2).mapToInt(Integer::valueOf).toArray();
String[] 转 int[]
int[] ints1 = Arrays.stream(arr3).mapToInt(Integer::valueOf).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是存的是int类型的stream,而Steam< Integer >是一个存了Integer的stream。boxed的作用就是将int类型的stream转成了Integer类型的Stream。