归约:
reduce(T identity, BinaryOperator)/reduce(BinaryOperator) —— 可以将流中元素反复结合起来,得到一个值。
备注:map 和 reduce 的连接通常称为 map-reduce 模式,因为 Google 用它来进行网络搜索而出名
收集:
collect —— 将流转换为其他形式。接收一个 Collector 接口的实现,用于给 Stream 中元素做汇总的方法。
/**
* 终止操作
*/
public class TestStreamAPI6 {
List<Employe> emps = Arrays.asList(
new Employe("张三", 18,9999.99, Status.FREE),
new Employe("李四", 38,5555.99, Status.BUSY),
new Employe("王五", 50,6666.66, Status.VOCATION),
new Employe("赵六", 16,3333.33, Status.FREE),
new Employe("田七", 10,7777.77, Status.BUSY),
new Employe("田七", 16,8888.88, Status.VOCATION)
);
/**
* 归约
* reduce(T identity, BinaryOperator)/reduce(BinaryOperator) —— 可以将流中元素反复结合起来,
* 得到一个值。
*/
@Test
public void test1(){
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = list.stream()
.reduce(0, (x, y) -> x + y);
System.out.println(sum);
System.out.println("-------------------------------------------");
//计算工资总和
Optional<Double> op = emps.stream()
.map(Employe::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
}
/**
* 收集:
* collect —— 将流转换为其他形式。接收一个Collector 接口的实现,
* 用于给 Stream 中元素做汇总的方法。
*/
@Test
public void test2(){
List<String> list = emps.stream()
.map(Employe::getName)
.collect(Collectors.toList());
list.forEach(x->System.out.print(x+"\t\t"));
System.out.println("\n ----------------------------------------------");
Set<String> set = emps.stream()
.map(Employe::getName)
.collect(Collectors.toSet());
set.forEach(x-> System.out.print(x+"\t\t"));
}
@Test
public void test3(){
//人员总数
Long count = emps.stream().count();
// .collect(Collectors.counting());
System.out.println("总数量:"+count);
//工资平均值
Double avgSalary = emps.stream()
.collect(Collectors.averagingDouble(Employe::getSalary));
System.out.println("平均工资:"+avgSalary);
//工资总和
Double sumSalary = emps.stream().mapToDouble(Employe::getSalary).sum();
// .collect(Collectors.summingDouble(Employe::getSalary));
System.out.println("工资总和:"+sumSalary);
//工资最大值
Optional<Employe> maxSalary = emps.stream()
.max(Comparator.comparingDouble(Employe::getSalary));
// .max((x, y) -> Double.compare(x.getSalary(), y.getSalary()));
// .collect(Collectors.maxBy((x, y) -> Double.compare(x.getSalary(), y.getSalary())));
System.out.println("工资最大值:"+ maxSalary.get().getSalary());
//工资最小值
Optional<Employe> minSalary = emps.stream()
.min(Comparator.comparingDouble(Employe::getSalary));
// .min((x, y) -> Double.compare(x.getSalary(), y.getSalary()));
// .collect(Collectors.minBy((x, y) -> Double.compare(x.getSalary(), y.getSalary())));
System.out.println("工资最小值:"+ minSalary.get().getSalary());
}
}