一、新特性总览

二、Lambda表达式
Lambda 是一个匿名函数,我们可以把Lambda 表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。使用它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。
2.1 Lambda表达式语法
# 语法格式一: 无参,无返回值
Runnable r1 =() -> {
System.out.printin("Hello Lambda!");
};
# 语法格式二: Lambda 需要一个参数,但是没有返回值
Consumer<String> con = (String str) -> {
System.out.printin(str);
);
# 语法格式三: 数据类型可以省略,因为可由编译器推断得出,称为“类型推断”
Consumer<String> con = (str) -> {
System.out.printin(str);
};
# 语法格式四: Lambda 若只需要一个参数时,参数的小括号可以省略
Consumer<String> con = str -> {
System.out.printin(str);
};
# 语法格式五: Lambda 需爱两个或以上的参数,多条执行语句,并且可以有返回值
Comparator<Integer> com = (x,y) -> {
System.out.println("实现函数式接口方法!");
return Integer.compare(x,y);
};
# 语法格式六: 当 Lambda 体只有一条语句时,return 与大括号若有,都可以省略
Comparator<Integer> com = (x,y) -> Integer.compare(x, y);
2.2 Lambda使用案例
/**
* Lambda表达式的使用
*
* 1.举例: (o1,o2) -> Integer.compare(o1,o2);
* 2.格式:
* -> :lambda操作符 或 箭头操作符
* ->左边:lambda形参列表 (其实就是接口中的抽象方法的形参列表)
* ->右边:lambda体 (其实就是重写的抽象方法的方法体)
*
* 3.Lambda表达式的本质: 作为接口的实例
*/
public class LambdaTest1 {
//语法格式一:无参,无返回值
@Test
public void test(){
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("长安欢迎您");
}
};
r1.run();
System.out.println("---------------------------");
Runnable r2 = () -> System.out.println("长安欢迎您");
r2.run();
}
//语法格式二:Lambda 需要一个参数,但是没有返回值。
@Test
public void test2(){
Consumer<String> con = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
con.accept("善与恶的区别是什么?");
System.out.println("---------------------------");
Consumer<String> c1 = (String s) -> {
System.out.println(s);
};
c1.accept("先天人性无善恶,后天人性有善恶。");
}
//语法格式三:数据类型可以省略,因为可由编译器推断得出,称为“类型推断”
@Test
public void test3(){
Consumer<String> c1 = (String s) -> {
System.out.println(s);
};
c1.accept("先天人性无善恶,后天人性有善恶。");
System.out.println("---------------------------");
Consumer<String> c2 = (s) -> {
System.out.println(s);
};
c2.accept("如果没有邪恶的话我们怎么会知道人世间的那些善良呢?");
}
//语法格式四:Lambda若只需要一个参数时,参数的小括号可以省略
@Test
public void test4(){
Consumer<String> c1 = (s) -> {
System.out.println(s);
};
c1.accept("先天人性无善恶,后天人性有善恶。");
System.out.println("---------------------------");
Consumer<String> c2 = s -> {
System.out.println(s);
};
c2.accept("如果没有邪恶的话我们怎么会知道人世间的那些善良呢?");
}
//语法格式五:Lambda需要两个或以上的参数,多条执行语句,并且可以有返回值
@Test
public void test5(){
Comparator<Integer> c1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
System.out.println(o1);
System.out.println(o2);
return o1.compareTo(o2);
}
};
System.out.println(c1.compare(15,23));
System.out.println("---------------------------");
Comparator<Integer> com2 = (o1,o2) -> {
System.out.println(o1);
System.out.println(o2);
return o1.compareTo(o2);
};
System.out.println(com2.compare(16,8));
}
//语法格式六:当Lambda体只有一条语句时,return与大括号若有,都可以省略
@Test
public void test6(){
Comparator<Integer> c1 = (o1,o2) -> {
return o1.compareTo(o2);
};
System.out.println(c1.compare(16,8));
System.out.println("---------------------------");
Comparator<Integer> c2 = (o1,o2) -> o1.compareTo(o2);
System.out.println(c2.compare(17,24));
}
}
三、函数式(Functional)接口
3.1 函数式接口的介绍
如果一个接口中,只声明了一个抽象方法,可以有其他默认方法,则此接口就称为函数式接口。我们可以在一个接口上使用 @FunctionalInterface 注解,
- 这样做可以检查它是否是一个函数式接口。
public interface MyInterFace {
void method();
}
- 在java.util.function包下定义了Java 8 的丰富的函数式接口
- Java从诞生日起就是一直倡导“一切皆对象”,在Java里面面向对象(OOP)编程是一切。但是随着python、scala等语言的兴起和新技术的挑战,Java不得不做出调整以便支持更加广泛的技术要求,也即java不但可以支持OOP还可以支持OOF(面向函数编程)
- 在函数式编程语言当中,函数被当做一等公民对待。在将函数作为一等公民的编程语言中,Lambda表达式的类型是函数。但是在Java8中,有所不同。在Java8中,Lambda表达式是对象,而不是函数,它们必须依附于一类特别的对象类型——函数式接口。
- 简单的说,在Java8中,Lambda表达式就是一个函数式接口的实例。这就是Lambda表达式和函数式接口的关系。也就是说,只要一个对象是函数式接口的实例,那么该对象就可以用Lambda表达式来表示。
- 所以以前用匿名实现类表示的现在都可以用Lambda表达式来写。
3.2 Java内置的函数式接口介绍及使用举例
| 函数式接口 | 参数类型 | 返回类型 | 用途 |
|---|---|---|---|
Consumer 消费型接口 | T | void | 对类型为T的对象应用操作,包含方法:void accept(T t) |
Supplier 供给型接口 | 无 | T | 返回类型为T的对象,包含方法:T get() |
Function<T, R>函数型接口 | T | R | 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t) |
Predicate断定型接口 | T | boolean | 确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法:boolean test(T t) |
BiFunction<T,U,R> | T, U | R | 对类型为T,U参数应用操作,返回R类型的结果。包含方法为:Rapply(T t,U u); |
UnaryOperator(Function子接口) | T | T | 对类型为T的对象进行一元运算,并返回T类型的结果。包含方法为:Tapply(T t); |
BinaryOperator(BiFunction子接口) | T,T | T | 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法为:Tapply(T t1,T t2); |
BiConsumer<T,U> | T,U | void | 对类型为T,U参数应用操作。包含方法为:voidaccept(Tt,Uu) |
BiPredicate<T,U> | T,U | boolean | 包含方法为:booleantest(Tt,Uu) |
ToIntFunction | T | int | 计算int值的函数 |
ToLongFunction | T | long | 计算long值的函数 |
ToDoubleFunction | T | double | 计算double值的函数 |
IntFunction | int | R | 参数为int类型的函数 |
LongFunction | long | R | 参数为long类型的函数 |
DoubleFunction | double | R | 参数为double类型的函数 |
/**
* java内置的4大核心函数式接口
*
* 消费型接口 Consumer<T> void accept(T t)
* 供给型接口 Supplier<T> T get()
* 函数型接口 Function<T,R> R apply(T t)
* 断定型接口 Predicate<T> boolean test(T t)
*/
public class LambdaTest2 {
public void happyTime(double money, Consumer<Double> con) {
con.accept(money);
}
@Test
public void test(){
happyTime(30, new Consumer<Double>() {
@Override
public void accept(Double aDouble) {
System.out.println("熬夜太累了,点个外卖,价格为:" + aDouble);
}
});
System.out.println("+++++++++++++++++++++++++");
//Lambda表达式写法
happyTime(20,money -> System.out.println("熬夜太累了,吃口麻辣烫,价格为:" + money));
}
//根据给定的规则,过滤集合中的字符串。此规则由Predicate的方法决定
public List<String> filterString(List<String> list, Predicate<String> pre){
ArrayList<String> filterList = new ArrayList<>();
for(String s : list){
if(pre.test(s)){
filterList.add(s);
}
}
return filterList;
}
@Test
public void test2(){
List<String> list = Arrays.asList("长安","上京","江南","渝州","凉州","兖州");
List<String> filterStrs = filterString(list, new Predicate<String>() {
@Override
public boolean test(String s) {
return s.contains("州");
}
});
System.out.println(filterStrs);
List<String> filterStrs1 = filterString(list,s -> s.contains("州"));
System.out.println(filterStrs1);
}
}
四、方法引用与构造器引用
- 当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
- 方法引用可以看做是Lambda表达式深层次的表达。换句话说,方法引用就是Lambda表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是Lambda表达式的一个语法糖。
- 要求:实现接口的抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致!
- 格式:使用操作符“::” 将类(或对象) 与方法名分隔开来。
- 如下三种主要使用情况:
对象::实例方法名类::静态方法名类::实例方法名
4.1 方法引用的对象 :: 非静态方法
Employee类
@Data
@ToString
@EqualsAndHashCode
public class Employee {
private int id;
private String name;
private int age;
private double salary;
}
测试类
/**
* 方法引用的使用
*
* 1.使用情境:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
*
* 2.方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以
* 方法引用,也是函数式接口的实例。
*
* 3. 使用格式: 类(或对象) :: 方法名
*
* 4. 具体分为如下的三种情况:
* 情况1 对象 :: 非静态方法
* 情况2 类 :: 静态方法
*
* 情况3 类 :: 非静态方法
*
* 5. 方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的
* 形参列表和返回值类型相同!(针对于情况1和情况2)
*/
public class MethodRefTest {
// 情况一:对象 :: 实例方法
//Consumer中的void accept(T t)
//PrintStream中的void println(T t)
@Test
public void test() {
Consumer<String> c1 = str -> System.out.println(str);
c1.accept("兖州");
System.out.println("+++++++++++++");
PrintStream ps = System.out;
Consumer<String> c2 = ps::println;
c2.accept("xian");
}
//Supplier中的T get()
//Employee中的String getName()
@Test
public void test2() {
Employee emp = new Employee(004,"Nice",19,4200);
Supplier<String> sk1 = () -> emp.getName();
System.out.println(sk1.get());
System.out.println("*******************");
Supplier<String> sk2 = emp::getName;
System.out.println(sk2.get());
}
}
4.2 方法引用的类 :: 静态方法
测试类
public class MethodRefTest {
// 情况二:类 :: 静态方法
//Comparator中的int compare(T t1,T t2)
//Integer中的int compare(T t1,T t2)
@Test
public void test3() {
Comparator<Integer> com1 = (t1, t2) -> Integer.compare(t1,t2);
System.out.println(com1.compare(21,20));
System.out.println("+++++++++++++++");
Comparator<Integer> com2 = Integer::compare;
System.out.println(com2.compare(15,7));
}
//Function中的R apply(T t)
//Math中的Long round(Double d)
@Test
public void test4() {
Function<Double,Long> func = new Function<Double, Long>() {
@Override
public Long apply(Double d) {
return Math.round(d);
}
};
System.out.println("++++++++++++++++++");
Function<Double,Long> func1 = d -> Math.round(d);
System.out.println(func1.apply(14.1));
System.out.println("++++++++++++++++++");
Function<Double,Long> func2 = Math::round;
System.out.println(func2.apply(17.4));
}
}
4.3 方法引用的类 :: 实例方法
测试类
public class MethodRefTest {
// 情况三:类 :: 实例方法 (有难度)
// Comparator中的int comapre(T t1,T t2)
// String中的int t1.compareTo(t2)
@Test
public void test5() {
Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
System.out.println(com1.compare("abc","abd"));
System.out.println("++++++++++++++++");
Comparator<String> com2 = String :: compareTo;
System.out.println(com2.compare("abd","abm"));
}
//BiPredicate中的boolean test(T t1, T t2);
//String中的boolean t1.equals(t2)
@Test
public void test6() {
BiPredicate<String,String> pre1 = (s1, s2) -> s1.equals(s2);
System.out.println(pre1.test("MON","MON"));
System.out.println("++++++++++++++++++++");
BiPredicate<String,String> pre2 = String :: equals;
System.out.println(pre2.test("MON","MON"));
}
// Function中的R apply(T t)
// Employee中的String getName();
@Test
public void test7() {
Employee employee = new Employee(007, "Ton", 21, 8000);
Function<Employee,String> func1 = e -> e.getName();
System.out.println(func1.apply(employee));
System.out.println("++++++++++++++++++++++++");
Function<Employee,String> f2 = Employee::getName;
System.out.println(f2.apply(employee));
}
}
4.4 构造器引用与数组引用
与函数式接口相结合,自动与函数式接口中方法兼容。
可以把构造器引用赋值给定义的方法,要求构造器参数列表要与接口中抽象方法的参数列表一致!且方法的返回值即为构造器对应类的对象。
测试类
/**
* 一、构造器引用
* 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
* 抽象方法的返回值类型即为构造器所属的类的类型
*
* 二、数组引用
* 可以把数组看做是一个特殊的类,则写法与构造器引用一致。
*/
public class MethodRefTest {
//构造器引用
//Supplier中的T get()
//Employee的空参构造器:Employee()
@Test
public void test() {
Supplier<Employee> sup = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
System.out.println("+++++++++++++++++++");
Supplier<Employee> sk1 = () -> new Employee();
System.out.println(sk1.get());
System.out.println("+++++++++++++++++++");
Supplier<Employee> sk2 = Employee::new;
System.out.println(sk2.get());
}
//Function中的R apply(T t)
@Test
public void test2() {
Function<Integer, Employee> f1 = id -> new Employee(id);
Employee employee = f1.apply(7793);
System.out.println(employee);
System.out.println("+++++++++++++++++++");
Function<Integer, Employee> f2 = Employee::new;
Employee employee1 = f2.apply(4545);
System.out.println(employee1);
}
//BiFunction中的R apply(T t,U u)
@Test
public void test3() {
BiFunction<Integer, String, Employee> f1 = (id, name) -> new Employee(id, name);
System.out.println(f1.apply(2513, "Fruk"));
System.out.println("+++++++++++++++++++");
BiFunction<Integer, String, Employee> f2 = Employee::new;
System.out.println(f2.apply(9526, "Bon"));
}
//数组引用
//Function中的R apply(T t)
@Test
public void test4() {
Function<Integer, String[]> f1 = length -> new String[length];
String[] arr1 = f1.apply(7);
System.out.println(Arrays.toString(arr1));
System.out.println("+++++++++++++++++++");
Function<Integer, String[]> f2 = String[]::new;
String[] arr2 = f2.apply(9);
System.out.println(Arrays.toString(arr2));
}
}
五、Stream API
5.1 Stream API的概述
- Java8中有两大最为重要的改变。第一个是Lambda 表达式;另外一个则是Stream API。
- Stream API ( java.util.stream)把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为Stream API可以极大提供Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
- Stream 是Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用SQL 执行的数据库查询。也可以使用Stream API 来并行执行操作。简言之,Stream API 提供了一种高效且易于使用的处理数据的方式。
- 为什么要使用Stream API
- 实际开发中,项目中多数数据源都来自于Mysql,Oracle等。但现在数据源可以更多了,有MongDB,Radis等,而这些NoSQL的数据就需要Java层面去处理。
- Stream 和Collection 集合的区别:Collection 是一种静态的内存数据结构,而Stream 是有关计算的。前者是主要面向内存,存储在内存中,后者主要是面向CPU,通过CPU 实现计算。
/**
* 1.Stream关注的是对数据的运算,与CPU打交道
* 集合关注的是数据的存储,与内存打交道
*
* 2.
* ①Stream 自己不会存储元素。
* ②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
* ③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
*
* 3.Stream 执行流程
* ① Stream的实例化
* ② 一系列的中间操作(过滤、映射、...)
* ③ 终止操作
*
* 4.说明:
* 4.1 一个中间操作链,对数据源的数据进行处理
* 4.2 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
*/

5.2 Stream的实例化
EmployeeData类
/**
* 提供用于测试的数据
*/
public class EmployeeData {
public static List<Employee> getEmployees(){
List<Employee> list = new ArrayList<>();
list.add(new Employee(1001, "马化腾", 34, 6000.38));
list.add(new Employee(1002, "马云", 12, 9876.12));
list.add(new Employee(1003, "刘强东", 33, 3000.82));
list.add(new Employee(1004, "雷军", 26, 7657.37));
list.add(new Employee(1005, "李彦宏", 65, 5555.32));
list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
return list;
}
}
Employee类同上
测试类
/**
* 测试Stream的实例化
*/
public class StreamAPITest {
//创建 Stream方式一:通过集合
@Test
public void test(){
List<Employee> employees = EmployeeData.getEmployees();
// default Stream<E> stream() : 返回一个顺序流
Stream<Employee> stream = employees.stream();
// default Stream<E> parallelStream() : 返回一个并行流
Stream<Employee> parallelStream = employees.parallelStream();
}
//创建 Stream方式二:通过数组
@Test
public void test2(){
int[] arr = new int[]{1,2,3,4,5,6};
//调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
IntStream stream = Arrays.stream(arr);
Employee e1 = new Employee(1001,"Hom");
Employee e2 = new Employee(1002,"Nut");
Employee[] arr1 = new Employee[]{e1,e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
}
//创建 Stream方式三:通过Stream的of()
@Test
public void test3(){
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
}
//创建 Stream方式四:创建无限流
@Test
public void test4(){
// 迭代
// public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
//遍历前10个偶数
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
}
5.3 Stream的中间操作:筛选与切片
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。
| 方法 | 描述 |
|---|---|
filter(Predicate p) | 接收Lambda ,从流中排除某些元素 |
distinct() | 筛选,通过流所生成元素的hashCode() 和equals() 去除重复元素 |
limit(long maxSize) | 截断流,使其元素不超过给定数量 |
skip(long n) | 跳过元素,返回一个扔掉了前n 个元素的流。若流中元素不足n 个,则返回一个空流。与limit(n)互补 |
/**
* 测试Stream的中间操作
*/
public class StreamAPITest2 {
//1-筛选与切片
@Test
public void test(){
List<Employee> list = EmployeeData.getEmployees();
// filter(Predicate p)——接收 Lambda , 从流中排除某些元素。
Stream<Employee> stream = list.stream();
//练习:查询员工表中薪资大于7000的员工信息
stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);
// limit(n)——截断流,使其元素不超过给定数量。
list.stream().limit(3).forEach(System.out::println);
// skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
list.stream().skip(3).forEach(System.out::println);
// distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
list.stream().distinct().forEach(System.out::println);
}
}
5.4 Stream的中间操作:映射
| 方法 | 描述 |
|---|---|
map(Function f) | 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。 |
mapToDouble(ToDoubleFunction f) | 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的DoubleStream。 |
mapToInt(ToIntFunction f) | 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的IntStream。 |
mapToLong(ToLongFunction f) | 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的LongStream。 |
flatMap(Function f) | 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流 |
/**
* 测试Stream的中间操作
*/
public class StreamAPITest2 {
//2-映射
@Test
public void test2(){
// map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。
List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
// 练习1:获取员工姓名长度大于3的员工的姓名。
List<Employee> employees = EmployeeData.getEmployees();
Stream<String> namesStream = employees.stream().map(Employee::getName);
namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
//练习2:
Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest2::fromStringToStream);
streamStream.forEach(s ->{
s.forEach(System.out::println);
});
System.out.println("++++++++++++++++++++++");
// flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
Stream<Character> characterStream = list.stream().flatMap(StreamAPITest2::fromStringToStream);
characterStream.forEach(System.out::println);
}
//将字符串中的多个字符构成的集合转换为对应的Stream的实例
public static Stream<Character> fromStringToStream(String str){//aa
ArrayList<Character> list = new ArrayList<>();
for(Character c : str.toCharArray()){
list.add(c);
}
return list.stream();
}
}
5.5 Stream的中间操作:排序
| 方法 | 描述 |
|---|---|
sorted() | 产生一个新流,其中按自然顺序排序 |
sorted(Comparator com) | 产生一个新流,其中按比较器顺序排序 |
/**
* 测试Stream的中间操作
*/
public class StreamAPITest2 {
//3-排序
@Test
public void test4(){
// sorted()——自然排序
List<Integer> list = Arrays.asList(25,45,36,12,85,64,72,-95,4);
list.stream().sorted().forEach(System.out::println);
//抛异常,原因:Employee没有实现Comparable接口
// List<Employee> employees = EmployeeData.getEmployees();
// employees.stream().sorted().forEach(System.out::println);
// sorted(Comparator com)——定制排序
List<Employee> employees = EmployeeData.getEmployees();
employees.stream().sorted( (e1,e2) -> {
int ageValue = Integer.compare(e1.getAge(),e2.getAge());
if(ageValue != 0){
return ageValue;
}else{
return -Double.compare(e1.getSalary(),e2.getSalary());
}
}).forEach(System.out::println);
}
}
5.6 Stream的终止操作:匹配与查找
- 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是void 。
- 流进行了终止操作后,不能再次使用。
| 方法 | 描述 |
|---|---|
allMatch(Predicate p) | 检查是否匹配所有元素 |
anyMatch(Predicate p) | 检查是否至少匹配一个元素 |
noneMatch(Predicate p) | 检查是否没有匹配所有元素 |
findFirst() | 返回第一个元素 |
findAny() | 返回当前流中的任意元素 |
count() | 返回流中元素总数 |
max(Comparator c) | 返回流中最大值 |
min(Comparator c) | 返回流中最小值 |
forEach(Consumer c) | 内部迭代(使用Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了) |
public class StreamAPITest3 {
//1-匹配与查找
@Test
public void test(){
List<Employee> employees = EmployeeData.getEmployees();
// allMatch(Predicate p)——检查是否匹配所有元素。
// 练习:是否所有的员工的年龄都大于18
boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 23);
System.out.println(allMatch);
// anyMatch(Predicate p)——检查是否至少匹配一个元素。
// 练习:是否存在员工的工资大于 10000
boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 9000);
System.out.println(anyMatch);
// noneMatch(Predicate p)——检查是否没有匹配的元素。
// 练习:是否存在员工姓“马”,有为false
boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("马"));
System.out.println(noneMatch);
// findFirst——返回第一个元素
Optional<Employee> employee = employees.stream().findFirst();
System.out.println(employee);
// findAny——返回当前流中的任意元素
Optional<Employee> employee1 = employees.parallelStream().findAny();
System.out.println(employee1);
}
@Test
public void test2(){
List<Employee> employees = EmployeeData.getEmployees();
// count——返回流中元素的总个数
long count = employees.stream().filter(e -> e.getSalary() > 4500).count();
System.out.println(count);
// max(Comparator c)——返回流中最大值
// 练习:返回最高的工资:
Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
Optional<Double> maxSalary = salaryStream.max(Double::compare);
System.out.println(maxSalary);
// min(Comparator c)——返回流中最小值
// 练习:返回最低工资的员工
Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(employee);
System.out.println();
// forEach(Consumer c)——内部迭代
employees.stream().forEach(System.out::println);
//使用集合的遍历操作
employees.forEach(System.out::println);
}
}
5.7 Stream的终止操作:归约
| 方法 | 描述 |
|---|---|
reduce(T iden, BinaryOperator b) | 可以将流中元素反复结合起来,得到一个值。返回T |
reduce(BinaryOperator b) | 可以将流中元素反复结合起来,得到一个值。返回Optional |
public class StreamAPITest3 {
//2-归约
@Test
public void test3(){
// reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
// 练习1:计算1-10的自然数的和
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//10+list的和
Integer sum = list.stream().reduce(10, Integer::sum);//65
// reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
// 练习2:计算公司所有员工工资的总和
List<Employee> employees = EmployeeData.getEmployees();
Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
// Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
Optional<Double> sumMoney = salaryStream.reduce((d1,d2) -> d1 + d2);
System.out.println(sumMoney.get());
}
}
5.8 Stream的终止操作:收集
| 方法 | 描述 |
|---|---|
collect(Collector c) | 将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法 |
public class StreamAPITest3 {
//3-收集
@Test
public void test4() {
// collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
// 练习1:查找工资大于6000的员工,结果返回为一个List或Set
List<Employee> employees = EmployeeData.getEmployees();
List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
employeeList.forEach(System.out::println);
Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Student {
private String name;
private Integer age;
private String sex;
}
@Test
public void test1() {
List<Student> list = new ArrayList<>();
list.add(new Student("张1", 1, "男"));
list.add(new Student("张2", 2, "男"));
list.add(new Student("张3", 3, "男"));
list.add(new Student("张4", 4, "女"));
list.add(new Student("张5", 5, "女"));
//按性别分组
Map<String, IntSummaryStatistics> map = list.stream()
.collect(Collectors.groupingBy(Student::getSex,
Collectors.summarizingInt(Student::getAge)));
map.entrySet().stream().forEach((Map.Entry entry) -> {
String sex = (String) entry.getKey();
IntSummaryStatistics value = (IntSummaryStatistics) entry.getValue();
System.out.println("性别:"+sex+",总数"+value.getSum());//性别:女,总数9
System.out.println("性别:"+sex+",个数"+value.getCount());//性别:女,个数2
System.out.println("性别:"+sex+",平均值"+value.getAverage());//性别:女,平均值4.5
System.out.println("性别:"+sex+",最大值"+value.getMax());//性别:女,最大值5
System.out.println("性别:"+sex+",最小值"+value.getMin());//性别:女,最小值4
});
}
Collector 接口中方法的实现决定了如何对流执行收集的操作(如收集到List、Set、Map)。
Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:


六、Optional类
6.1 Optional类的介绍
到目前为止,臭名昭著的空指针异常是导致Java应用程序失败的最常见原因。以前,为了解决空指针异常,Google公司著名的Guava项目引入了Optional类,Guava通过使用检查空值的方式来防止代码污染,它鼓励程序员写更干净的代码。受到Google Guava的启发,Optional类已经成为Java 8类库的一部分。
- Optional 类(java.util.Optional) 是一个容器类,它可以保存类型T的值,代表这个值存在。或者仅仅保存null,表示这个值不存在。原来用null 表示一个值不存在,现在Optional 可以更好的表达这个概念。并且可以避免空指针异常。
- Optional类的Javadoc描述如下:这是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
- Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
- 创建Optional类对象的方法:
- Optional.of(T t): 创建一个Optional 实例,t必须非空;
- Optional.empty() : 创建一个空的Optional 实例
- Optional.ofNullable(T t):t可以为null
- 判断Optional容器中是否包含对象:
- boolean isPresent() : 判断是否包含对象
- void ifPresent(Consumer<? super T> consumer) :如果有值,就执行Consumer接口的实现代码,并且该值会作为参数传给它。
- 获取Optional容器的对象:
- T get(): 如果调用对象包含值,返回该值,否则抛异常
- T orElse(T other) :如果有值则将其返回,否则返回指定的other对象。
- T orElseGet(Supplier<? extends T> other) :如果有值则将其返回,否则返回由Supplier接口实现提供的对象。
- T orElseThrow(Supplier<? extends X> exceptionSupplier) :如果有值则将其返回,否则抛出由Supplier接口实现提供的异常。
6.2 Optional类使用
@Data
@AllArgsConstructor
@NoArgsConstructor
class Student {
private String name;
private Integer age;
}
1、创建Optional类
public void test1() {
// 声明一个空Optional
Optional<Object> empty = Optional.empty();
System.out.println(empty);//Optional.empty
// 依据一个非空值创建Optional
Student student = new Student();
Optional<Student> os1 = Optional.of(student);
System.out.println(os1);//Optional[Student(name=null, age=null)]
// 可接受null的Optional
Student student1 = null;
Optional<Student> os2 = Optional.ofNullable(student1);
System.out.println(os2);//Optional.empty
}
2、判断Optional容器中是否包含对象
isPresent不带参数,判断是否为空,ifPresent可以选择带一个消费函数的实例。(isPresent和ifPresent一个是 is 一个是 if 注意一下哈)
public void test1() {
Student student = new Student();
Optional<Student> os1 = Optional.ofNullable(student);
boolean present = os1.isPresent();
System.out.println(present);//true
// 利用Optional的ifPresent方法做出如下:当student不为空的时候将name赋值为张三
Optional.ofNullable(student).ifPresent(p -> p.setName("张三"));
System.out.println(student);//Student(name=张三, age=null)
}
3、获取Optional容器的对象
public void test1() throws Exception {
Student student = null;
Optional<Student> os1 = Optional.ofNullable(student);
// 使用get一定要注意,假如student对象为空,get是会报错的
//Student student1 = os1.get();// java.util.NoSuchElementException: No value present
// 当student为空的时候,声明一个对象
Student student2 = os1.orElse(new Student("张三", 18));
System.out.println(student2);//Student(name=张三, age=18)
// orElseGet就是当student为空的时候,返回通过Supplier供应商函数创建的对象
Student student3 = os1.orElseGet(() -> new Student("李四", 20));
System.out.println(student3);//Student(name=李四, age=20)
// orElseThrow就是当student为空的时候,可以抛出我们指定的异常
os1.orElseThrow(() -> new RuntimeException());//java.lang.RuntimeException
}
4、过滤
public void test1() {
Student student = new Student("李四", 3);
Optional<Student> os1 = Optional.ofNullable(student);
//过滤姓名为张三的学生,如果存在输出OK
os1.filter(p -> p.getName().equals("张三")).ifPresent(x -> System.out.println("OK"));
}
六、日期时间API
背景
java.util.Date和Calendar类的问题:
- 可变性:像日期和时间这样的类应该是不可变的。
- 偏移性:Date中的年份是从1900开始的,而月份都从0开始。
- 格式化:格式化只对Date有用,Calendar则不行。
- 此外,它们也不是线程安全的;不能处理闰秒等。
@Test
public void testDate(){
//偏移量
Date date1 = new Date(2020,9,8);
System.out.println(date1); //Fri Oct 08 00:00:00 CST 3920
Date date2 = new Date(2020 - 1900,9 - 1,8);
System.out.println(date2); //Tue Sep 08 00:00:00 CST 2020
}
第三次引入的API是成功的,并且Java 8中引入的java.time API 已经纠正了过去的缺陷,将来很长一段时间内它都会为我们服务。
Java 8 吸收了Joda-Time 的精华,以一个新的开始为Java 创建优秀的API。新的java.time 中包含了所有关于本地日期(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类。历史悠久的Date 类新增了toInstant()方法,用于把Date 转换成新的表示形式。这些新增的本地化时间日期API 大大简化了日期时间和本地化的管理。
6.1 LocalDate、LocalTime、LocalDateTime的使用
- LocalDate、LocalTime、LocalDateTime类是其中较重要的几个类,它们的实例是不可变的对象,分别表示使用ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储生日、纪念日等日期。LocalTime表示一个时间,而不是日期。LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一。
- 注:ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法,也就是公历。
@Test
public void test1(){
//now():获取当前的日期、时间、日期+时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);//2023-03-08
System.out.println(localTime);//13:52:01.051
System.out.println(localDateTime);//2023-03-08T13:52:01.051
//of():设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1);//2020-10-06T13:23:43
//getXxx():获取相关的属性
System.out.println(localDateTime.getDayOfMonth());//8
System.out.println(localDateTime.getDayOfWeek());//WEDNESDAY
System.out.println(localDateTime.getMonth());//MARCH
System.out.println(localDateTime.getMonthValue());//3
System.out.println(localDateTime.getMinute());//52
//体现不可变性
//withXxx():设置相关的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);//2023-03-08
System.out.println(localDate1);//2023-03-22
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);//2023-03-08T13:52:01.051
System.out.println(localDateTime2);//2023-03-08T04:52:01.051
//不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);//2023-03-08T13:52:01.051
System.out.println(localDateTime3);//2023-06-08T13:52:01.051
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);//2023-03-08T13:52:01.051
System.out.println(localDateTime4);//2023-03-02T13:52:01.051
}

6.2 Instant类的使用
Instant:时间线上的一个瞬时点。这可能被用来记录应用程序中的事件时间戳。- 在处理时间和日期的时候,我们通常会想到年,月,日,时,分,秒。然而,这只是时间的一个模型,是面向人类的。第二种通用模型是面向机器的,或者说是连续的。在此模型中,时间线中的一个点表示为一个很大的数,这有利于计算机处理。在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中,也是从1970年开始,但以毫秒为单位。
-java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位。Instant表示时间线上的一点,而不需要任何上下文信息,例如,时区。概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的秒数。因为java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级。
(1 ns = 10-9s) 1秒= 1000毫秒=106微秒=109纳秒
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
@Test
public void test2(){
//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant);//2023-03-08T05:58:14.528Z
//添加时间的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));//东八区
System.out.println(offsetDateTime);//2023-03-08T13:58:14.528+08:00
//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ---> Date类的getTime()
long milli = instant.toEpochMilli();
System.out.println(milli);//1678255094528
//ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)
Instant instant1 = Instant.ofEpochMilli(1678255094528L);
System.out.println(instant1);//2023-03-08T05:58:14.528Z
}
6.3 DateTimeFormatter的使用
java.time.format.DateTimeFormatter 类:该类提供了三种格式化方法:
- 预定义的标准格式。如:
ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME - 本地化相关的格式。如:
ofLocalizedDateTime(FormatStyle.LONG) - 自定义的格式。如:
ofPattern(“yyyy-MM-dd hh:mm:ss”)

@Test
public void test3(){
//方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//格式化:日期-->字符串
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter.format(localDateTime);
System.out.println(localDateTime);//2023-03-08T14:14:07.276
System.out.println(str1);//2023-03-08T14:14:07.276
//解析:字符串 -->日期
TemporalAccessor parse = formatter.parse("2020-05-10T18:26:40.234");
System.out.println(parse);//{},ISO resolved to 2020-05-10T18:26:40.234
//方式二:
//本地化相关的格式。如:ofLocalizedDateTime()
//FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
String str2 = formatter1.format(localDateTime);
System.out.println(str2);//2023年3月8日 下午02时14分07秒
//本地化相关的格式。如:ofLocalizedDate()
//FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String str3 = formatter2.format(LocalDate.now());
System.out.println(str3);//2023-3-8
//重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String str4 = formatter3.format(LocalDateTime.now());
System.out.println(str4);//2023-03-08 02:14:07
//解析
TemporalAccessor accessor = formatter3.parse("2020-05-10 06:26:40");
System.out.println(accessor);
//{MicroOfSecond=0, HourOfAmPm=6, SecondOfMinute=40, MinuteOfHour=26, MilliOfSecond=0, NanoOfSecond=0},ISO resolved to 2020-05-10
}
6.4 其它日期时间相关API的使用
- ZoneId:该类中包含了所有的时区信息,一个时区的ID,如Europe/Paris
- ZonedDateTime:一个在ISO-8601日历系统时区的日期时间,如2007-12-03T10:15:30+01:00Europe/Paris。
- 其中每个时区都对应着ID,地区ID都为“{区域}/{城市}”的格式,例如:Asia/Shanghai等
@Test
public void test1(){
//ZoneId:类中包含了所有的时区信息
// ZoneId的getAvailableZoneIds():获取所有的ZoneId
Set<String> zoneIds= ZoneId.getAvailableZoneIds();
for(String s: zoneIds) {
System.out.println(s);
}
// ZoneId的of():获取指定时区的时间
LocalDateTime localDateTime= LocalDateTime.now(ZoneId.of("Asia/Tokyo"));//日本时间
System.out.println(localDateTime);//2023-03-08T15:18:25.248
//ZonedDateTime:带时区的日期时间
// ZonedDateTime的now():获取本时区的ZonedDateTime对象
ZonedDateTime zonedDateTime= ZonedDateTime.now();
System.out.println(zonedDateTime);//2023-03-08T14:18:25.253+08:00[Asia/Shanghai]
// ZonedDateTime的now(ZoneId id):获取指定时区的ZonedDateTime对象
ZonedDateTime zonedDateTime1= ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(zonedDateTime1);//2023-03-08T15:18:25.254+09:00[Asia/Tokyo]
}
- Clock:使用时区提供对当前即时、日期和时间的访问的时钟。
- 持续时间:Duration,用于计算两个“时间”间隔
- 日期间隔:Period,用于计算两个“日期”间隔
- TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下一个工作日”等操作。
- TemporalAdjusters : 该类通过静态方法(firstDayOfXxx()/lastDayOfXxx()/nextXxx())提供了大量的常用TemporalAdjuster 的实现。
@Test
public void test2(){
//Duration:用于计算两个“时间”间隔,以秒和纳秒为基准
LocalTime localTime= LocalTime.now();
LocalTime localTime1= LocalTime.of(15, 23, 32);
//between():静态方法,返回Duration对象,表示两个时间的间隔
Duration duration= Duration.between(localTime1, localTime);
System.out.println(duration);//PT-47M-23.186S
System.out.println(duration.getSeconds());//-2844
System.out.println(duration.getNano());//814000000
LocalDateTime localDateTime= LocalDateTime.of(2016, 6, 12, 15, 23, 32);
LocalDateTime localDateTime1= LocalDateTime.of(2017, 6, 12, 15, 23, 32);
Duration duration1= Duration.between(localDateTime1, localDateTime);
System.out.println(duration1.toDays());//-365
}
@Test
public void test3(){
//Period:用于计算两个“日期”间隔,以年、月、日衡量
LocalDate localDate= LocalDate.now();
System.out.println(localDate);//2023-03-08
LocalDate localDate1= LocalDate.of(2028, 3, 18);
Period period= Period.between(localDate, localDate1);
System.out.println(period);//P5Y10D
System.out.println(period.getYears());//5
System.out.println(period.getMonths());//0
System.out.println(period.getDays());//10
Period period1= period.withYears(2);
System.out.println(period1);//P2Y10D
}
参考:与传统日期处理的转换



2462

被折叠的 条评论
为什么被折叠?



