目录
本文用到的类 Employee
一、Optional容器类
package stream;
import java.util.Optional;
import org.junit.Test;
public class OptionalTest {
@Test
public void optionalTest(){
Employee employee = new Employee(1007, "任正非", 26, 4333.32);
Optional<Employee> optional = Optional.of(employee); // 创建optional实例,把对象装到optional容器,对象不能为null
System.out.println(optional);
// 判断
System.out.println("***********present************");
Employee e = null;
Optional<Employee> nullOptional = Optional.ofNullable(null); // 创建optional实例,把对象装到optional容器,对象可以为null
boolean notPresent = nullOptional.isPresent(); // 容器中是否包含对象,null不为对象
System.out.println(notPresent);
nullOptional.ifPresent(emp -> System.out.println(emp.getName())); //如果有对象就执行,没有就不执行,此处不执行
Optional<Employee> employeeOptional = Optional.ofNullable(employee);
employeeOptional.ifPresent(emp -> System.out.println(emp.getName())); //此处执行
//如果有对象就执行,没有就执行runnable
nullOptional.ifPresentOrElse(emp -> System.out.println(emp.getName()), () -> System.out.println("此optional没有对象"));
System.out.println("***********isEmpty************");
boolean empty = nullOptional.isEmpty(); // 是否为空,null也为空
System.out.println(empty);
Optional<Employee> emptyOptional = Optional.empty(); // 创建空实例
boolean empty11 = emptyOptional.isEmpty();
System.out.println(empty11);
// 获取optional内的对象
System.out.println("***********获取对象************");
Employee employee1 = optional.get(); // 直接获取
System.out.println(employee1.getName());
Employee zkbg = emptyOptional.orElse(new Employee(1008, "扎克伯格", 35, 2500.32)); // 如果是空,就是参数的对象
System.out.println(zkbg.getName());
Employee lj = emptyOptional.orElseGet(() -> new Employee(1004, "雷军", 26, 7657.37));// 如果是空,就是Supplier提供的对象
System.out.println(lj.getName());
try {
emptyOptional.orElseThrow(() -> new Throwable("出现异常了")); // 如果是空,就抛出Supplier提供的异常
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
二、StreamAPI的使用
package stream;
import java.util.ArrayList;
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;
import org.junit.Test;
public class StreamStudy {
@Test // Stream实例化
public void streamAPITest(){
List<Employee> list = EmployeeData.getEmployees();
// list对象直接调用stream相关方法
Stream<Employee> stream = list.stream();// 顺序流
Stream<Employee> parallelStream = list.parallelStream();// 并行流
// 通过数组
Employee[] arr = new Employee[]{new Employee(1001, "马化腾", 34, 6000.38)
,new Employee(1002, "马云", 12, 9876.12)
,new Employee(1003, "刘强东", 33, 3000.82)};
Stream<Employee> employeeStream = Arrays.stream(arr);
// 通过Stream静态方法
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
// 创建无限流
Stream<Integer> iterateStream = Stream.iterate(0, t -> t + 2).limit(10);
Stream<Double> generateStream = Stream.generate(Math::random).limit(10);
}
@Test // 中间操作
public void streamAPITest1(){
List<Employee> list = EmployeeData.getEmployees();
// 1.筛选与切片
System.out.println("********filter********");
Stream<Employee> stream = list.stream();
stream.filter(employee -> employee.getSalary() > 7000).forEach(System.out::println);
System.out.println("********limit********");
stream = list.stream();
stream.limit(3).forEach(System.out::println);
System.out.println("*******skip*********");
stream = list.stream();
stream.skip(5).forEach(System.out::println);
System.out.println("********distinct********");
stream = list.stream();
stream.distinct().forEach(System.out::println);
// 2.映射
System.out.println("*******map*********");
stream = list.stream();
stream.map(employee -> employee.getName()).forEach(System.out::println);
System.out.println("********map********");
List<String> list1 = new ArrayList<>();
String[] strs = new String[]{"ab","cde"};
Stream<String> stream1 = Arrays.stream(strs);
// 每个Stream作为一个外层stream的元素
Stream<Stream<Character>> streamStream = stream1.map(str -> stringToStream(str));
streamStream.forEach(System.out::println);
System.out.println("*******flatMap*********");
list1 = new ArrayList<>();
strs = new String[]{"fg","hij"};
stream1 = Arrays.stream(strs);
// 每个Stream内的元素都氮素作为一个外层stream的元素
Stream<Character> characterStream = stream1.flatMap(str -> stringToStream(str));
characterStream.forEach(System.out::println);
// 3.排序
System.out.println("*******sorted自然排序*********");
Stream<Employee> streamE = list.stream();
streamE.sorted().forEach(System.out::println);
System.out.println("*******sorted定制排序*********");
Stream<Employee> streamF = list.stream();
streamF.sorted((e1,e2) -> Double.compare(e1.getSalary() , e2.getSalary())).forEach(System.out::println);
}
@Test // 终止操作
public void streamAPITest2(){
List<Employee> list = EmployeeData.getEmployees();
// 匹配与查找
System.out.println("********allMatch********");
Stream<Employee> stream = list.stream();
System.out.println(stream.allMatch(employee -> employee.getSalary() > 5000)); // 是否全部匹配
System.out.println("********allMatch********");
stream = list.stream();
System.out.println(stream.anyMatch(employee -> employee.getSalary() > 5000)); // 是否有匹配的
System.out.println("********noneMatch********");
stream = list.stream();
System.out.println(stream.noneMatch(employee -> employee.getSalary() > 5000)); // 是否没有匹配的
System.out.println("********findFirst********");
stream = list.stream();
Optional<Employee> first = stream.findFirst(); // 查找第一个
System.out.println(first);
System.out.println("********findAny********");
stream = list.parallelStream();
Optional<Employee> any = stream.findAny(); // 查找任一一个
System.out.println(any);
System.out.println("********max********");
stream = list.stream();
Optional<Employee> max = stream.max((a, b) -> Double.compare(a.getSalary(), b.getSalary())); // 最大的对象
System.out.println(max);
System.out.println("********min********");
stream = list.stream();
Optional<Double> aDouble = stream.min((a, b) -> Double.compare(a.getSalary(), b.getSalary())).map(a -> a.getSalary()); //最小的对象的某属性
System.out.println(aDouble);
System.out.println("********forEach********");
stream = list.stream();
stream.forEach(System.out::println); // 内部迭代操作
// 规约
System.out.println("********reduce********");
stream = list.stream();
Optional<Double> aDouble1 = stream.map(e -> e.getSalary()).reduce(Double::sum);
//Double aDouble1 = stream.map(e -> e.getSalary()).reduce(0.0, (a, b) -> Double.sum(a, b)); // 等价
//Double aDouble1 = stream.map(e -> e.getSalary()).reduce(0.0, (a, b) -> a - b); // 等价
System.out.println(aDouble1);
// 收集
System.out.println("********reduce********");
stream = list.stream();
List<Employee> collect = stream.filter(s -> s.getSalary() > 6000).collect(Collectors.toList());
System.out.println(collect);
System.out.println("********reduce********");
stream = list.stream();
Set<String> set = stream.map(e -> e.getName()).collect(Collectors.toSet());
System.out.println(set);
}
Stream<Character> stringToStream(String str){
List<Character> list = new ArrayList<>();
for (Character c: str.toCharArray()) {
list.add(c);
}
Stream<Character> stream = list.stream();
return stream;
}
}