Stream的终止操作:终止操作会从流的流水线生成结果,其结果可以是任何不适流的操作,例如:List,Integer,甚至是void
一,查找与匹配
List<Employee> employeeList1 = Arrays.asList(
new Employee("cdy1",18,1772.22),
new Employee("cdy2",18,1872.22),
new Employee("cdy3",18,1672.22),
new Employee("cdy4",18,1972.22)
);
List<Employee> employeeList2 = Arrays.asList(
new Employee("cdy1",18,1772.22),
new Employee("cdy2",19,1872.22),
new Employee("cdy3",11,1672.22),
new Employee("cdy4",18,1972.22)
);
说明:Predicate 是断言型函数式接口;
1、allMatch(Predicate p) 检查流中所有元素是否都满足条件,返回boolean值
@Test
public void test1(){
boolean b1 = employeeList1.stream().allMatch((e) -> {
if (e.getAge() == 18 || e.getSalary() == 1972.22) {
return true;
}
return false;
});
System.out.println(b1);//truw
boolean b2 = employeeList2.stream().allMatch((e) -> {
if (e.getAge() == 18 || e.getSalary() == 1972.22) {
return true;
}
return false;
});
System.out.println(b2); //false
}
2、anyMatch(Predicate p) 检查所有元素中至少有一个元素满足条件
@Test
public void test2() {
boolean b = employeeList1.stream().anyMatch((e) -> e.getAge() == 18);
System.out.println(b);//true
}
3、noneMatch(Predicate p) 所有元素都不满足条件返回true,否则false
@Test
public void test3() {
boolean b = employeeList1.stream().noneMatch((e) -> e.getAge() == 0);
System.out.println(b);//true
}
4、findFirst() 返回第一个元素
@Test
public void test4() {
Optional<Employee> first = employeeList1.stream()
.sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
System.out.println(first.get().getSalary());//1672.22
}
5、findAny() 返回当前流中的任意元素
@Test
public void test5() {
Optional<Employee> any = employeeList1.stream().findAny();
System.out.println(any.get().getSalary());//1772.22
}
6.reduce(T iden, BinaryOperator b) (规约)可以将流中元素反复结合起来,得到一个值。返回 T
@Test
public void test8() {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Integer reduce = integers.stream().reduce(3, (x, y) -> x + y);
System.out.println(reduce);
}
7.collect(Collector c) 将流转换为其他形式。接收一个 Collector接口的 实现,用于给Stream中元素做汇总的方法
@Test
public void test9() {
List<Integer> collect = employeeList2.stream().map(Employee::getAge).collect(Collectors.toList());
collect.forEach(System.out::println);
Set<String> collect1 = employeeList2.stream().map(Employee::getName).collect(Collectors.toSet());
collect1.forEach(System.out::print);
employeeList2.stream().collect(Collectors.toCollection(HashSet::new));
}