import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* stream终止操作
*/
public class StreamAPITest2 {
//1-匹配与查找
@Test
public void test1() {
List<Employee> employees = EmployData.getEmployees();
//allMatch(Predicate p) - 检查是否匹配所有的元素
boolean allMatch = employees.stream().allMatch((e) -> e.getAge() > 18);
System.out.println("allMatch = " + allMatch);
//anyMatch(Predicate p)-检查是否至少一个满足条件
boolean anyMatch = employees.stream().anyMatch((e) -> e.getSalary() > 10000);
System.out.println("anyMatch = " + anyMatch);
//noneMatch(Predicate p)-检查是否没有一个满足条件
boolean noneMatch = employees.stream().noneMatch((e) -> e.getName().startsWith("雷"));
System.out.println("noneMatch = " + noneMatch);
//findFirst()
Optional<Employee> first = employees.stream().findFirst();
System.out.println("first = " + first);
//findAny 返回任意元素
Optional<Employee> any = employees.parallelStream().findAny();
System.out.println("any = " + any);
}
@Test
public void test2() {
List<Employee> employees = EmployData.getEmployees();
//count -返回流中的元素个数
long count = employees.stream().filter((e) -> e.getSalary() > 5000).count();
System.out.println("count = " + count);
//max(Comparator c) -返回流中的最大值
//返回最高的工资
Stream<Double> doubleStream = employees.stream().map((e) -> e.getSalary());
Optional<Double> max = doubleStream.max(Double::compareTo);
System.out.println("max = " + max);
//min(Comparator c) -返回流中的最小值
//返回工资最低的员工
Optional<Employee> min = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println("min = " + min);
employees.stream().forEach(System.out::println);
//使用集合的遍历方式
employees.forEach(System.out::println);
}
/**
* 2-规约
*/
@Test
public void test3(){
//reduce(T identity,BinaryOperation) -可以将流中的元素反复结合起来得到一个值
//练习1.计算1-10自然数的和
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer reduce = list.stream().reduce(0, Integer::sum);
System.out.println("reduce = " + reduce);
//reduce(BinaryOperation) -可以将流中的元素反复结合起来得到一个值。返回Optional<>
//计算工资的和
List<Employee> employees = EmployData.getEmployees();
Stream<Double> doubleStream = employees.stream().map(Employee::getSalary);
Optional<Double> sumSalary = doubleStream.reduce(Double::sum);
System.out.println("sumSalary = " + sumSalary);
}
/**
* 3-收集
*/
@Test
public void test4(){
//collect(Collector c) -将流转换为其他形式。接收一个collector接口的实现用于给
//练习1:查找工资大于6000的员工,结果返回一个list或set
List<Employee> employees = EmployData.getEmployees();
List<Employee> employeeList = employees.stream().filter((e) -> e.getSalary() > 6000).collect(Collectors.toList());
System.out.println("employeeList = " + employeeList);
Set<Employee> employeeSet = employees.stream().filter((e) -> e.getSalary() > 6000).collect(Collectors.toSet());
System.out.println("employeeSet = " + employeeSet);
}
}
Stream终止操作
最新推荐文章于 2024-07-06 11:38:18 发布