Java8 Stream
Stream
Stream 就如同一个迭代器(Iterator),单向,不可往复,数据只能遍历一次,遍历过一次后即用尽了,就好比流水从面前流过,一去不复返。
Stream流的操作符分为两类:
中间操作符和终止操作符。
Stream 的一系列操作必须要使用终止操作,否则整个数据流是不会流动起来的,即处理操作不会执行。
中间操作符
map
map(mapToInt,mapToLong,mapToDouble) 转换操作符,把比如A->B,这里默认提供了转int,long,double的操作符。
public class Main {
public static void main(String[] args) {
Stream.of("apple","banana","orange","waltermaleon","grape")
.map(e->e.length()) //转成单词的长度 int
.forEach(e->System.out.println(e)); //输出
}
}
flatmap
flatmap(flatmapToInt,flatmapToLong,flatmapToDouble) 拍平操作比如把 int[]{2,3,4} 拍平 变成 2,3,4 也就是从原来的一个数据变成了3个数据,这里默认提供了拍平成int,long,double的操作符。
public class Main {
public static void main(String[] args) {
Stream.of("a-b-c-d","e-f-i-g-h")
.flatMap(e->Stream.of(e.split("-")))
.forEach(e->System.out.println(e));
}
}
limit
limit 限流操作,比如数据流中有10个 我只要出前3个就可以使用。
public class Main {
public static void main(String[] args) {
Stream.of(1,2,3,4,5,6)
.limit(3) //限制三个
.forEach(e->System.out.println(e)); //将输出 前三个 1,2,3
}
}
distint
distint 去重操作,对重复元素去重,底层使用了equals方法。
filter
filter 过滤操作,把不想要的数据过滤。
filter 对某些元素进行过滤,不符合筛选条件的将无法进入流的下游。
peek
peek 挑出操作,如果想对数据进行某些操作,如:读取、编辑修改等。
public class Main {
public static void main(String[] args) {
Stream.of(1,2,3,1,2,5,6,7,8,0,0,1,2,3,1)
.filter(e->e>=5) //过滤小于5的
.forEach(e->System.out.println(e));
}
}
skip
skip 跳过操作,跳过某些元素。
public class Main {
public static void main(String[] args) {
Stream.of(1,2,3,4,5,6,7,8,9)
.skip(4) //跳过前四个
.forEach(e->System.out.println(e)); //输出的结果应该只有5,6,7,8,9
}
}
sorted
sorted(unordered) 排序操作,对元素排序,前提是实现Comparable接口,当然也可以自定义比较器。
底层依赖Comparable 实现,也可以提供自定义比较器
public class Main {
public static void main(String[] args) {
Stream.of(2,1,3,6,4,9,6,8,0)
.sorted()
.forEach(e->System.out.println(e));
}
}
终止操作符
collect
collect 收集操作,将所有数据收集起来,这个操作非常重要,官方的提供的Collectors 提供了非常多收集器,可以说Stream 的核心在于Collectors。
collect 收集,使用系统提供的收集器可以将最终的数据流收集到List,Set,Map等容器中。
count
count 统计操作,统计最终的数据个数。
findFirst
findFirst、findAny 查找操作,查找第一个、查找任何一个 返回的类型为Optional。
public class FindFirst {
public static void main(String[] args) {
Optional<String> stringOptional = Stream.of("apple", "banana", "orange", "waltermaleon", "grape")
.findFirst();
stringOptional.ifPresent(e->System.out.println(e));
}
}
allMatch
noneMatch、allMatch、anyMatch 匹配操作,数据流中是否存在符合条件的元素 返回值为bool 值。
min
min、max 最值操作,需要自定义比较器,返回数据流中最大最小的值。
public class Main {
public static void main(String[] args) {
Optional<Integer> integerOptional = Stream.of(0,9,8,4,5,6,-1)
.min((e1,e2)->e1.compareTo(e2));
integerOptional.ifPresent(e->System.out.println(e));
}
reduce
reduce 规约操作,将整个数据流的值规约为一个值,count、min、max底层就是使用reduce。
reduce 是一个规约操作,所有的元素归约成一个,比如对所有元素求和,乘啊等。
public class Main {
public static void main(String[] args) {
int sum = Stream.of(0,9,8,4,5,6,-1)
.reduce(0,(e1,e2)->e1+e2);
System.out.println(sum);
}
}
forEach
forEach、forEachOrdered 遍历操作,这里就是对最终的数据进行消费了。
toArray
toArray 数组操作,将数据流的元素转换成数组。