Stream流List、int[]相互转化
一、 int[ ] 转换成List
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
list.forEach(e -> System.out.print(e + " "));
}
- Arrays.stream(arr) 将int数组转化为IntStream
- boxed() 将每一个整数进行装箱,把IntStream 转换成了 Stream< Integer >
- collect(Collectors.toList()) 将对象流收集为集合,转化为 List< Integer >
二、List转换成int[ ]
int[] arr2 = list.stream().mapToInt(Integer::valueOf).toArray();
- mapToInt(Integer::valueOf) 将对象流转化为基本类型流
- toArray() 转化为int数组