List 转 Array 数组
引用类型
给一个 List 类型集合,将其转为对应元素类型的数组
List<T> list = new ArrayList<>();
T[] arr = list.toArray(new T[0]);
其中 T 是指泛型,使用时转换为对应元素类型即可
基本类型
如果是集合内的元素属于基本类型,如 int、double,那么需要通过 StreamAPI
List<Integer> list = new ArrayList<>();
int[] ints = list.stream().mapToInt(Integer::intValue).toArray();
其中,mapToInt() 方法根据类型变化
Array 转 List
- 获取 Stream 对象
- 使用 Stream API 的 collect 方法(若是基本类型的数组,则需要装箱)
若要转换的数组元素类型是基本类型,则需要先将 stream 装箱boxed才能通过 Stream API 转 list
int[] arr = new int[]{1, 2, 3, 4};
List<Integer> collect = Arrays.stream(arr).boxed().collect(Collectors.toList());
若不是基本类型,则可以直接转
String[] str = new String[]{"1", "2", "3", "4"};
List<String> collect = Arrays.stream(str).collect(Collectors.toList());

本文介绍了如何在Java中将List转换为Array及反之的方法。包括使用通用类型转换、Stream API进行基本类型处理,以及利用Stream API结合collectors将Array转换为List。
416

被折叠的 条评论
为什么被折叠?



