查找与匹配
- 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。
方法 | 描述 |
---|
allMatch(Predicate p) | 检查是否匹配所有元素 |
anyMatch(Predicate p) | 检查是否至少匹配一个元素 |
noneMatch(Predicate p) | 检查是否没有匹配所有元素 |
findFirst() | 返回第一个元素 |
findAny() | 返回当前流中的任意元素 |
count() | 返回流中总数 |
max(Comparator c) | 返回流中最大值 |
min(Comparator c) | 返回流中最小值 |
forEach(Consumer c) | 内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了) |
归约
方法 | 描述 |
---|
reduce(T iden, BinaryOperator b) | 可以将流中元素反复结合起来,得到一个值。返回 T |
reduce(BinaryOperator b) | 可以将流中元素反复结合起来,得到一个值。返回 Optional<T> |
@Test
public void test1(){
List<Integer> list = Arrays.asList(1,2,3,4);
Integer sum = list.stream().reduce(0, (x, y) -> x + y);
System.out.println(sum);
}
收集
方法 | 描述 |
---|
collect (Collector c) | 将流转换为其他形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法 |
- Collector接口中方法的实现决定了如何对流执行收集操作(如收集到List,Set,Map).但是Collectors实现类中提供了许多静态方法,可以方便的创建常见的收集器实例.


package mao.shu;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TestJava8_10 {
List<Employee> employeeList = Arrays.asList(
new Employee("xiemaoshu", 23, 5000.0),
new Employee("lanchaogou", 23, 10000.0),
new Employee("xxx", 30, 3000.0),
new Employee("yyy", 40, 2000.0),
new Employee("yyy", 40, 2000.0)
);
@Test
public void test1(){
List<Integer> list = Arrays.asList(1,2,3,4);
Integer sum = list.stream().reduce(0, (x, y) -> x + y);
System.out.println(sum);
}
@Test
public void test2(){
List<Employee> collect = employeeList.stream().collect(Collectors.toList());
collect.stream().forEach(System.out::println);
System.out.println("--------------------------");
Set<Employee> employeeSet = employeeList.stream().collect(Collectors.toSet());
employeeSet.stream().forEach(System.out::println);
ArrayList<Employee> collect1 = employeeList.stream().collect(Collectors.toCollection(ArrayList::new));
Long collect2 = employeeList.stream().collect(Collectors.counting());
System.out.println(collect2);
IntSummaryStatistics sum = employeeList.stream().collect(Collectors.summarizingInt(Employee::getAge));
System.out.println(sum);*/
Double avg = employeeList.stream().collect(Collectors.averagingDouble(Employee::getSarlay));
System.out.println(avg);
}
@Test
public void test3(){
String collect = employeeList.stream().map(Employee::getName).collect(Collectors.joining());
System.out.println(collect);
}
}