最近在leetcode上刷算法,总能遇到数组和List之间来回转换的问题,记录一下,希望大伙能用的上。以下内容均为作者自己摸索出来的,如果有更优雅的写法,可以评论区留言交流~~~
对象类型
演示类
public class Foo {
private final String bar;
public Foo(String bar) {
this.bar = bar;
}
}
数组转List
List<Foo> fooList = Arrays.asList(fooArr);
List转数组
注意 这里的声明的数组的大小不代表最终转换后数组的大小,不需要传入真实的数组大小,传入0即可。
Foo[] foos = fooList.toArray(new Foo[0]);
二维数组转List
Foo[][] fooArr = new Foo[4][4];
List<List<Foo>> collect = Arrays.stream(fooArr)
.map(Arrays::asList)
.collect(Collectors.toList());
嵌套List转数组
List<List<Foo>> collect = new ArrayList<>();
Foo[][] foos1 = collect.stream()
.map(foos -> foos.toArray(new Foo[0]))
.toArray(Foo[][]::new);
基本类型
基本数组类型需要先转换成对应的IntStream,FloatStream...然后才能转换成数组或List
数组转List
int[] nums = new int[4];
List<Integer> collect = IntStream.of(nums)
.boxed()
.collect(Collectors.toList());
List转数组
ArrayList<Integer> intList = new ArrayList<>();
int[] ints = intList.stream()
.mapToInt(value -> value)
.toArray();
二维数组转List
int[][] ints = new int[4][4];
List<List<Integer>> collect = Arrays.stream(ints)
.map(a -> IntStream.of(a).boxed().collect(Collectors.toList()))
.collect(Collectors.toList());
List转二维数组
注意 这里最后的数组需要标注collect的长度,否则,会转换失败
List<List<Integer>> collect = new ArrayList<>();
int[][] ints1 = collect.stream()
.map(a -> a.stream().mapToInt(value -> value).toArray())
.toArray(a -> new int[collect.size()][0]);