// 将 List 元素存储到数组中
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
// 将数组元素 存储到 List 中
int[] arr = {1, 2, 3, 4, 5};
List<Integer> list = IntStream.of(arr).boxed().collect(Collectors.toList());
短短几行就实现了数组与集合的相互转换,之前不适用流进行操作的话,就需要循环进行叠加,相对较麻烦,也不利于代码的可读性。
list.stream().mapToInt:这个我们可以理解为将integer类型的集合元素转换为流,然后通过Integer::intValue形式取出来,在使用.toArray()进行组装为数组。
IntStream.of(arr).boxed():这个可以理解为将数组arr以int型数组进行展示,放在一个容器中,收集为一个list