Stream实现收集分组归约
package com.atguigu.java8;
import com.sun.media.jfxmediaimpl.HostUtils;
import org.testng.annotations.Test;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
/**
* @version 1.0
* @Author 罗宗苇
* @Date 2021/10/12 8:49
* @注释
*/
// API:应用程序编程接口
// Optional 中有处理空字符串的功能
/*
* allMatch:检查是否匹配所有的元素,boolean allMatch(Predicate<? super T> predicate);
* anyMatch:检查是否至少匹配一次 boolean anyMatch(Predicate<? super T> predicate);
* noneMatch:检查是否没有匹配所有元素
* */
public class TestStreamAPI3 {
List<Employee> employees = Arrays.asList(
new Employee("张三", 18, 1132, Employee.Status.FREE),
new Employee("李四", 48, 1232, Employee.Status.BUSY),
new Employee("王五", 18, 3432, Employee.Status.VOCATION),
new Employee("赵六", 67, 1432, Employee.Status.FREE),
new Employee("赵六", 12, 1432, Employee.Status.FREE),
new Employee("罗湖", 12, 1432, Employee.Status.FREE),
new Employee("史蒂夫", 50, 2342, Employee.Status.FREE)
);
/*
* 收集
* collect——将流转换为其他形式,接受一个Collector接口实现,用于给Stream中元素做汇总方法
* */
@Test
public void test10(){
String str = employees.stream()
.map(Employee::getName)
.collect(Collectors.joining(",","===","===z"));
System.out.println(str);
}
@Test
public void test9(){
DoubleSummaryStatistics dss = employees.stream()
.collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(dss.getAverage());
System.out.println(dss.getMax());
System.out.println(dss.getSum());
}
//分区
@Test
public void test8(){
Map<Boolean, List<Employee>> map = employees.stream()
.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 1500));
Iterator it = map.entrySet().iterator();
while (it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":" + value);
}
}
//多级分组
@Test
public void test7(){
Map<Employee.Status, Map<String, List<Employee>>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (e.getAge() <= 35) {
return "青年";
} else if (e.getAge() <= 50) {
return "中年";
} else {
return "老年";
}
})));
Iterator it = map.entrySet().iterator();
while (it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":" + value);
}
}
//分组
@Test
public void test6(){
Map<Employee.Status,List<Employee>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getStatus));
Iterator it = map.entrySet().iterator();
while (it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":" + value);
}
}
@Test
public void test5(){
//总数
Long count = employees.stream()
.collect(Collectors.counting());
System.out.println(count);
//平均值
Double avg = employees.stream()
.collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
//总和
Double sum = employees.stream()
.collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
//最大值
Optional<Employee> max = employees.stream()
.collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(max);
//最小值
Optional<Double> min = employees.stream()
.map(Employee::getSalary)
.collect(Collectors.minBy(Double::compare));
System.out.println();
}
@Test
public void test4(){
List<String> list = employees.stream()
.map(Employee::getName)
.collect(Collectors.toList());
list.forEach(System.out::println);
System.out.println("--------------------------------");
Set<String> set = employees.stream()
.map(Employee::getName)
.collect(Collectors.toSet());
set.forEach(System.out::println);
System.out.println("------------------------");
HashSet<String> hashSet = employees.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hashSet.forEach(System.out::println);
}
//归约 T reduce(T identity, BinaryOperator<T> accumulator)
// Optional<T> reduce(BinaryOperator<T> accumulator)
@Test
public void test3(){
List<Integer> list = Arrays.asList(1,2,3,4,5,3,5,3);
//因为该sum有初始值为0,不可能再为空
Integer sum = list.stream()
.reduce(0,(x, y) -> x + y);
System.out.println(sum);
//该sum是Double中的静态方法,可能为空
Optional<Double> op = employees.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
}
@Test
public void test2(){
long count = employees.stream()
.count();
System.out.println(count);
//找到工资的最大值
Optional<Employee> op = employees.stream()
.max((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()));
System.out.println(op.get());
//找到年龄的最小值
Optional<Employee> op2 = employees.stream()
.min((e1,e2) -> Integer.compare(e1.getAge(),e2.getAge()));
System.out.println(op2.get());
//找到工资的最小值,使用Stream API 中引用传递的特性
Optional<Double> op3 = employees.stream()
//将Employee中的getSalary提取出来形成一个Double集合
.map(Employee::getSalary)
//在Double集合中找出最小值,并返回一个Double类型的值
.min(Double::compare);
System.out.println(op3.get());
}
@Test
public void test1(){
boolean b1 = employees.stream()
.allMatch((e) -> e.getStatus().equals(Employee.Status.FREE));
System.out.println(b1);
boolean b2 = employees.stream()
.anyMatch((e) -> e.getStatus().equals(Employee.Status.FREE));
System.out.println(b2);
boolean b3 = employees.stream()
.noneMatch((e) -> e.getStatus().equals(Employee.Status.VOCATION));
System.out.println(b3);
//Optional 可是处理空指针异常
Optional<Employee> op = employees.stream()
//先进行从小到大排序,返回最小值;从大到小返回最大值
.sorted((e1, e2) -> Double.compare(e1.getSalary(),e2.getSalary()))
.findFirst(); //返回第一个值
System.out.println(op.get());
System.out.println("--------------------------");
Optional<Employee> op2 = employees.parallelStream()
.filter((e) -> e.getStatus().equals(Employee.Status.FREE))
.findAny();
System.out.println(op2.get());
}
}