5、collector——将stream流中的元素收集起来
<R, A> R collect(Collector<? super T, A, R> collector); Collector<? super T, A, R> collector 是一个接口,需用现实类来操作。jdk8提供了Collector接口的工具类Collectors用于将元素收集为list 、set 、map等
实例:
Book book = new Book("JAVA","ALIS", Book.Status.Busy,1009);
Book book2 = new Book("JAVASE","MARRY",Book.Status.Busy,393.234);
Book book3 = new Book("JAVAEE","LUCY",Book.Status.Free,3434.112);
Book book4 = new Book("MYBATIS","DANDAN",Book.Status.Busy,3423.12);
//收集名字放到list中(注:同时可收集到set集合或map集合等中)
ArrayList<Book> books = new ArrayList<>();
books.add(book);
books.add(book2);
books.add(book3);
books.add(book4);
List<String> collect = books.stream()
.map(Book::getName)
.collect(Collectors.toList());
System.out.println(collect);
结果:[JAVA, JAVASE, JAVAEE, MYBATIS]
//收集书价格的平均值
Double collect2 = books.stream()
.collect(Collectors.averagingDouble(Book::getPrice));
System.out.println("收集书价格的平均值:"+collect2);
//收集记录的总数
Long collect1 = books.stream()
.collect(Collectors.counting());
System.out.println("总数:"+collect1);
4、归约——reduce,可以将流中元素反复结合起来,得到一个值T。
T reduce(T identity, BinaryOperator<T> accumulator); identity:起始值,BinaryOperator二元操作,有起始值返回具体的类型
Optional<T> reduce(BinaryOperator<T> accumulator);BinaryOperator 二元操作,没有起始值,返回Optional,可能会为空
实例:
List<String> list = Arrays.asList("dd","wno","cc","bb");
String dd = list.stream()
.reduce("dd", (str1, str2) -> str1 + "," + str2);//有起始值
System.out.println("有起始值返回String类型:"+dd);
Optional<String> reduce = list.stream()
.reduce((x, y) -> x + "," + y);
System.out.println("没有起始值返回Optional类型,可能会为空"+reduce);
String s = reduce.get();
System.out.println("reduce.get()方法:"+s);
结果:
有起始值返回String类型:dd,dd,wno,cc,bb
没有起始值返回Optional类型,可能会为空Optional[dd,wno,cc,bb]
reduce.get()方法:dd,wno,cc,bb
1、stream终止操作——查找与匹配
stream.forEach()——终止操作。
allMatch——检查是否匹配所有元素
anyMatch——检查是否至少匹配一个元素
2、映射
map
3、其他中间操作
filter 过滤——筛出某些元素