stream的基本使用
为什么应该掌握
java stream已经出现好久了,类中提供了许多流式方法,可以让我们的代码看起来十分优雅。
读完这篇能学到什么
各种类型的转换,比如list转int,如果平时可能会这么写
int[] nums = new int[list.size()];
for (int i = 0; i < nums.length; i++) {
nums[i] = list.get(i);
}
学完之后
int[] ints = list.stream().mapToInt(v -> v).toArray();
是不是感觉清爽,干净很多。
开始使用
各种类型转数组
int[] ints = list.stream().mapToInt(v -> v).toArray();
int[] ints1 = set.stream().mapToInt(v -> v).toArray();
int[] ints2 = Arrays.stream(integers).mapToInt(v -> v).toArray();
int[] ints3 = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
规律,首先创建stream对象,通过mapToInt转化类型,里面是一个lambda表达式,指各种类型向int类型的转化。最后调用toArray。
转list
List<Integer> list1 = Arrays.stream(ints).boxed().toList();
List<Integer> list3 = Arrays.stream(strings).map(Integer::parseInt).toList();
List<Integer> list4 = Arrays.stream(integers).toList();
List<Integer> list2 = set.stream().toList();
转成stream,再调用toList。想办法将其他类型转int,数组转成包装类型。
转Integer[]
Integer[] integers1 = Arrays.stream(ints).boxed().toArray(Integer[]::new);
Integer[] integers2 = Arrays.stream(strings).map(Integer::parseInt).toArray(Integer[]::new);
Integer[] integers3 = Arrays.stream(integers).toArray(Integer[]::new);
Integer[] integers4 = set.stream().toArray(Integer[]::new);
先转成stream,再用toArray进一步转换
其他
以后再说