Java8特性
1 Lambda表达式
Lambda是一个匿名函数,可以把Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。使用它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。
1.1 案例一
package com.java8;
import java.util.Comparator;
/**
* @author LanceQ
* @date 2021年10月31日 19:37
*/
public class LambdaTest {
public static void main(String[] args) {
test1();
System.out.println("-------------------------------------");
test2();
}
//比较
private static void test2() {
Comparator<Integer> com1=new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1,o2);
}
};
int compare = com1.compare(20, 90);
System.out.println("小于输出:"+compare);
//lambda表达式的写法
Comparator<Integer> comparator2=(o1,o2) ->Integer.compare(o1,o2);
int compare1 = comparator2.compare(90, 60);
System.out.println("大于输出:"+compare1);
//方法引用
Comparator<Integer> comparator3=Integer::compare;
int compare2 = comparator2.compare(50, 50);
System.out.println("等于输出:"+compare2);
}
//输出
private static void test1() {
Runnable r1=new Runnable() {
@Override
public void run() {
System.out.println("Runnable····");
}
};
r1.run();
Runnable r2=()->System.out.println("lambda······");
r2.run();
}
}
1.2 案例二
package com.java8;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.function.Consumer;
/**
* @author LanceQ
* @date 2021年10月31日 20:14
* 格式:
* ---lambda操作符
* ---左边:lambda形参·列表(其实就是接口中的抽象放啊的形参列表)
* ---右边:lambda体(其实就是重新的抽象方法的方法体)
*
*
* 总结:
* ->左边:lambda形参列表的参数类型可以省略,如果lambda形参列表只有一个参数,其一对()也可以省略,
* 没有参数或者两个及以上不可以省略
* ->右边:lambda体应该使用一对{}包裹,如果lambda体只有一条执行语句(可能是return语句),
* 可以省略这一对{}和return
*
* lambda表达式的本质:作为接口(函数式接口)的实例(接口的实例化)
*
* 如果一个接口,只声明了一个抽象方法,则此接口就称为函数式接口(如:Runnable)
*
* 在一个接口上使用@Functionallnterface 注解,这样做可以检查它是否是一个函数式接口。
* 同时javadoc也会包含一条声明,说明这个接口是一个函数式接口。
*
* 以前用匿名实现类表示的现在都可以用Lambda表达式来写
*/
public class LambdaTest1 {
public static void main(String[] args) {
test();
System.out.println("--------------------------");
test2();
System.out.println("--------------------------");
test3();
System.out.println("--------------------------");
test4();
System.out.println("--------------------------");
test5();
System.out.println("--------------------------");
test6();
}
//6. 当lambda体只有一条语句时,return大括号若有,都可以省略
private static void test6() {
Comparator<Integer> com=new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
System.out.println(com.compare(58,3));
Comparator<Integer> com2=((o1, o2) -> o1.compareTo(o2));
System.out.println(com.compare(6,30));
}
//5. lambda如果需要两个或以上的参数,多条执行语句,可以有返回值
private static void test5() {
Comparator<Integer> com=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(com.compare(58,3));
Comparator<Integer> com2=((o1, o2) -> {
System.out.println(o1);
System.out.println(o2);
return o1.compareTo(o2);
});
System.out.println(com.compare(6,30));
}
//4.lambda若只有一个参数的时候,参数的小括号可以省略
private static void test4() {
Consumer<String> con=(String s)-> {
System.out.println(s);
};
con.accept("呜呜呜");
Consumer<String> con1= s-> System.out.println(s);;
con1.accept("嘤嘤嘤");
}
private static void t() {
//类型推断(省略后面的类型)
ArrayList<String> list=new ArrayList<>();
int[] arr=new int[]{1,2,3};
//类型推断
int[] arr1={1,2,3};
}
//3. 数据类型可用省略,因为可由编译器推断得出,称为“类型推断”
private static void test3() {
Consumer<String> con=(String s)-> {
System.out.println(s);
};
con.accept("呜呜呜");
Consumer<String> con1=(s)-> {
System.out.println(s);
};
con1.accept("喵喵喵");
}
//2.一个参数,无返回值
private static void test2() {
Consumer<String> con=new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
con.accept("嘤嘤嘤");
Consumer<String> con2=(String s)-> System.out.println(s);
Consumer<String> con3=(String s)-> {
System.out.println(s);
};
con2.accept("呜呜呜");
}
//1. 无参,无返回值
private static void test() {
Runnable r1=new Runnable() {
@Override
public void run() {
System.out.println("Runnable····");
}
};
r1.run();
Runnable r2=()->System.out.println("lambda······");
r2.run();
}
}
2 函数式接口(functional)
2.1 函数式接口介绍
- 只包含一个抽象方法的接口,称为函数式接口。
- 可以通过Lambda表达式来创建该接口的对象。(若Lambda表达式抛出一个受检异常(即:非运行时异常),那么该异常需要在目标接口的抽象方法上进行声明)。
- 我们可以在一个接口上使用@Functionallnterface 注解,这样做可以检查它是否是一个函数式接口。同时javadoc也会包含一条声明,说明这个接口是一个函数式接口。
- 在java.util.function包下定义了Java8的丰富的函数式接口。
2.2 函数式接口理解
- Java从诞生日起就是一直侣导“一切皆对象 ”,在Java里面面向对象(OOP)编程是一切。但是随着python、scala等语言的兴起和新技术的挑战,Java不得不做出调整以便支持更加广泛的技术要求,也即java不但可以支持OOP还可以支持OOF(面向函数编程)
- 在函数式编程语言当中,函数被当做一等公民对待。在将函数作为一等公民的编程语言中,Lambda表达式的类型是函数。但是在Java8中,有所不同。在Java8中,Lambda表达式是对象,而不是函数,它们必须依附于一类特别的对象类型——函数式接口。
- 简单的说,在Java8中,Lambda表达式就是一个函数式接口的实例。这就是Lambda表达式和函数式接口的关系。也就是说,只要一个对象是函数式接口的实例,那么该对象就可以用Lambda表达式来表示。
- 所以以前用匿名实现类表示的现在都可以用Lambda表达式来写。
2.3 java内置四大核心函数式接口
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
Consumer< T > :消费型接口 | T | void | 对类型为T的对象应用操作,包含方法:void accept(T t) |
Supplier< T > :供给型接口 | 无 | T | 返回类型为T的对象,包含方法:T get() |
Function< T,R > :函数型接口 | T | R | 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:void R apply(T t) |
Predicate< T > :断定型接口 | T | boolean | 确定类型为T的对象是否满足某约束,并返回boolean值。包含方法:boolean test(T t) |
消费型:有参数,无返回
供给型:无参数,有返回
函数型:有参数,又返回
断定型:有参数,返回为boolean型
例子:
package com.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* @author LanceQ
* @date 2021年11月07日 13:14
*
* java内置四大核心函数式接口
*
* 消费型接口 Consumer<T> void accept(T t)
* 供给型接口 Supplier<T> T get()
* 函数型接口 Function<T,R> R apply(T t)
* 断定型接口 Predicate<T,boolean> boolean test(T t)
*/
public class LambdaTest2 {
public static void main(String[] args) {
test1();
System.out.println("**************************");
test2();
}
private static void test2() {
LambdaTest2 test2 = new LambdaTest2();
List<String> list= Arrays.asList("背景","北京","南京","东经","西京");
List<String> list1 = test2.filterString(list, new Predicate<String>() {
@Override
public boolean test(String s) {
return s.contains("京");
}
});
System.out.println(list1);
//filterString方法的list参数是否包含京
List<String> list2 = test2.filterString(list, s -> s.contains("京"));
System.out.println(list2);
}
//根据给定的规则,过滤集合中的字符串,此规则由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;
}
private static void test1() {
LambdaTest2 lambdaTest2 = new LambdaTest2();
lambdaTest2.happyTime(500, new Consumer<Double>() {
@Override
public void accept(Double aDouble) {
System.out.println("消费了:"+aDouble);
}
});
int m = 400;
lambdaTest2.happyTime(m, money->System.out.println("使用了:"+money));
lambdaTest2.happyTime(300, money->System.out.println("使用了:"+money));
}
public void happyTime(double money, Consumer<Double> com){
com.accept(money);
}
}
运行结果:
消费了:500.0
使用了:400.0
使用了:300.0
**************************
[北京, 南京, 西京]
[北京, 南京, 西京]
3 方法引用与构造器引用
3.1 方法引用(Mehtod References)
- 当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
- 方法引用可以看做是Lambda表达式深层次的表达。换句话说,方法引用就是Lambda表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是Lambda表达式的一个语法糖。
- 要求:实现接口的抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致!
- 格式:使用操作符“∵”将类(或对象)与方法名分隔开来。
如下三种主要使用情况:
对象∵实例方法名
类::静态方法名
类::实例方法名
package com.java8.methodReferences;
import java.util.Objects;
/**
* @author LanceQ
* @date 2021年11月07日 22:03
*/
public class Employee {
private int id;
private String name;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee() {
System.out.println("Employee().....");
}
public Employee(int id) {
this.id = id;
System.out.println("Employee(int id).....");
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Employee employee = (Employee) o;
if (id != employee.id) {
return false;
}
if (age != employee.age) {
return false;
}
if (Double.compare(employee.salary, salary) != 0) {
return false;
}
return Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
temp = Double.doubleToLongBits(salary);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
package com.java8.methodReferences;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author LanceQ
* @date 2021/11/7 22:17
* 提供用于测试的数据
*/
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;
}
}
package com.java8.methodReferences;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
*
* @author LanceQ
* @date 2021年11月07日 22:18
* 方法引用的使用
*
* 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)
*/
public void test1() {
Consumer<String> con1 = str -> System.out.println(str);
con1.accept("北京");
System.out.println("*******************");
PrintStream ps = System.out;
Consumer<String> con2 = ps::println;
con2.accept("beijing");
}
/**
* Supplier中的T get()
* Employee中的String getName()
*/
public void test2() {
Employee emp = new Employee(1001,"Tom",23,5600);
Supplier<String> sup1 = () -> emp.getName();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<String> sup2 = emp::getName;
System.out.println(sup2.get());
}
/**
* 情况二:类 :: 静态方法
* Comparator中的int compare(T t1,T t2)
* Integer中的int compare(T t1,T t2)
*/
public void test3() {
Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
System.out.println(com1.compare(12,21));
System.out.println("*******************");
Comparator<Integer> com2 = Integer::compare;
System.out.println(com2.compare(12,3));
}
/**
* Function中的R apply(T t)
* Math中的Long round(Double d)
*/
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(12.3));
System.out.println("*******************");
Function<Double,Long> func2 = Math::round;
System.out.println(func2.apply(12.6));
}
/**
* 情况三:类 :: 实例方法 (有难度)
* Comparator中的int comapre(T t1,T t2)
* String中的int t1.compareTo(t2)
*/
public void test5() {
Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
//返回int类型
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)
*/
public void test6() {
BiPredicate<String,String> pre1 = (s1,s2) -> s1.equals(s2);
System.out.println(pre1.test("abc","abc"));
System.out.println("*******************");
BiPredicate<String,String> pre2 = String :: equals;
System.out.println(pre2.test("abc","abd"));
}
/**
* Function中的R apply(T t)
* Employee中的String getName();
*/
public void test7() {
Employee employee = new Employee(1001, "Jerry", 23, 6000);
Function<Employee,String> func1 = e -> e.getName();
System.out.println(func1.apply(employee));
System.out.println("*******************");
Function<Employee,String> func2 = Employee::getName;
System.out.println(func2.apply(employee));
}
}
package com.java8.methodReferences;
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @author LanceQ
* @date 2021年11月07日 22:14
* 一、构造器引用
* 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
* 抽象方法的返回值类型即为构造器所属的类的类型
*
* 二、数组引用
* 大家可以把数组看做是一个特殊的类,则写法与构造器引用一致。
*
*
*/
public class ConstructorRefTest {
public static void main(String[] args) {
test1();
test2();
test3();
test4();
}
/**
* 构造器引用
* Supplier中的T get()
* Employee的空参构造器:Employee()
*/
public static void test1(){
Supplier<Employee> sup = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
System.out.println("*******************");
Supplier<Employee> sup1 = () -> new Employee();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<Employee> sup2 = Employee :: new;
System.out.println(sup2.get());
}
/**
* Function中的R apply(T t)
*/
public static void test2(){
Function<Integer,Employee> func1 = id -> new Employee(id);
Employee employee = func1.apply(1001);
System.out.println(employee);
System.out.println("*******************");
Function<Integer,Employee> func2 = Employee :: new;
Employee employee1 = func2.apply(1002);
System.out.println(employee1);
}
/**
* BiFunction中的R apply(T t,U u)
*/
public static void test3(){
BiFunction<Integer,String,Employee> func1 = (id, name) -> new Employee(id,name);
System.out.println(func1.apply(1001,"Tom"));
System.out.println("*******************");
BiFunction<Integer,String,Employee> func2 = Employee :: new;
System.out.println(func2.apply(1002,"Tom"));
}
/**
* 数组引用
* Function中的R apply(T t)
*/
public static void test4(){
Function<Integer,String[]> func1 = length -> new String[length];
String[] arr1 = func1.apply(5);
System.out.println(Arrays.toString(arr1));
System.out.println("*******************");
Function<Integer,String[]> func2 = String[] :: new;
String[] arr2 = func2.apply(10);
System.out.println(Arrays.toString(arr2));
}
}
4 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提供了一种高效且易于使用的处理数据的方式。
- 实际开发中,项目中多数数据源都来自于MySQL,Oracle等。但现在数据源可以更多了,有MongDB,Radis等,而这些NoSQt的数据就需要Java层面去处理。
- Stream 和 Collectidn集合的区别:Collection是一种静态的内存数据结构,而Stream是有关计算的。前者是主要面向内存,存储在内存中。后者主要是面向CPU,通过CPU实现计算。
4.1 stream介绍
stream是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。“集合讲的是数据,Stream讲的是计算!”
注意:
- stream 自己不会存储元素。
- stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。
- stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
4.1.1 创建stream
一个数据源(如:集合、数组),获取一个流。
4.1.2 中间操作
一个中间操作链,对数据源的数据进行处理。
4.1.3 终端(终止)操作
一旦执行终止操作,就执行中间操作链,并产生结果,之后,不会再被使用。
4.2 Stream操作流程
4.2.1 创建stream
package com.java8.javaStream;
import com.java8.methodReferences.Employee;
import com.java8.methodReferences.EmployeeData;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* @author LanceQ
* @date 2021年11月14日 13:39
*
* 1. stream是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
* “集合讲的是数据,Stream讲的是计算!”
*
* 2.
* stream 自己不会存储元素。
* stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。
* stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
*
* 3.stream流程
* stream实例化
* 一系列中间操作(过滤、映射)
* 终止操作
*
* 4.
* 一个中间操作链,对数据源的数据进行处理
* 一旦执行终止操作,就执行中间操作链,并产生结果,之后,不会再被使用。
*/
public class StreamApiTest {
public static void main(String[] args) {
}
/**
* 创建stream方法一:通过集合
*/
public void test1(){
List<Employee> employees = EmployeeData.getEmployees();
//default Stream<E> stream():返回一个顺序流(顺序的取数据)
Stream<Employee> stream = employees.stream();
//default Stream<E> parallelStream():返回一个并行流(并行的取数据,得到的数据顺序可能混混乱)
Stream<Employee> employeeStream = employees.parallelStream();
}
/**
* 创建stream 二 :通过数组
*/
public void test2(){
int[] arr = {1, 2, 3, 4, 5, 6};
//调用Arrays类的static<T> Stream<T> stream(T[] Array):返回一个流
IntStream stream = Arrays.stream(arr);
//范型
Employee e1=new Employee(1001,"Tom");
Employee e2=new Employee(1002,"JJ");
Employee[] arr1=new Employee[]{e1,e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
Stream<Employee> objectStream = Stream.of(e1,e2);
}
/**
* 创建stream方法三:通过Stream的of()
*/
public void test3(){
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);
}
/**
* 创建stream方法四,创建无限流
*/
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)
//生成10个随机数
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
}
4.2.2 中间操作
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理。而在终止操作时一次性全部处理,称为“惰性求值”。
4.2.2.1 筛选和切片
- filter(Predicate P):接收Lambda,从流中排除元素
- distinct():筛选,通过流生成元素的hashCode()和equals()去除重复元素
- limit():截断流,使其元素不超过给定的数量
- skip(long n):跳过元素,放回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补。
4.2.2.2 映射
- map(Function f):接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
- mapToDouble(ToDoubleFunction f):接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的DoubleStream
- mapToInt(ToIntFunction f):接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的IntStream
- mapToLong(ToLongFunction f):接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的LongStream
- flatMap(Function f):接收一个函数作为参数,将流中的每一值都换成另一个流,然后把所有流连接成一个流
package com.java8.javaStream;
import com.java8.methodReferences.Employee;
import com.java8.methodReferences.EmployeeData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
* @author LanceQ
* @date 2021年11月14日 20:14
*
* stream的中间操作
*/
public class StreamApiTest1 {
public static void main(String[] args) {
//test1();
test2();
}
/**
* 映射
*/
private static void test2() {
//map(Function f):接收一个函数作为参数,将元素转换成其他形式或提取信息,
// 该函数会被应用到每个元素上,并将其映射成一个新的元素(全部转换成大写),映射过程中科院处理元素
List<String> list= Arrays.asList("aa","bb","cc","dd");
list.stream().map(str->str.toUpperCase()).forEach(System.out::println);
System.out.println("------------");
//获取员工姓名长度大于3的姓名
List<Employee> employees = EmployeeData.getEmployees();
employees.stream()
//.map(e->e.getName())下同
.map(Employee::getName)
.filter(e->e.length()>3)
.forEach(System.out::println);
//flatMap(Function f):接收一个函数作为参数,将流中的每一值都换成另一个流,然后把所有流连接成一个流
System.out.println("------------");
ArrayList list1=new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
ArrayList list2=new ArrayList<>();
list2.add(4);
list2.add(5);
list2.add(6);
//list1.add(list2);//-->map[1, 2, 3, [4, 5, 6]]
System.out.println(list1);
//--->flatMap,addAll会打散再添加[1, 2, 3, 4, 5, 6]
list1.addAll(list2);
System.out.println(list1);
Stream<Stream<Character>> streamStream = list.stream().map(StreamApiTest1::formStringToStream);
//双重循环
streamStream.forEach(s ->{
s.forEach(System.out::println);
});
//集合里面套集合的可以用flatMap
Stream<Character> characterStream = list.stream().flatMap(StreamApiTest1::formStringToStream);
characterStream.forEach(System.out::println);
}
/**
* 将字符串中的多个字符构成的集合转换为对应的Stream实例
*/
public static Stream<Character> formStringToStream(String str){
ArrayList<Character> list = new ArrayList<>();
for(Character c:str.toCharArray()){
list.add(c);
}
return list.stream();
}
private static void test1() {
List<Employee> employees = EmployeeData.getEmployees();
//1. filter(Predicate P):接收Lambda,从流中排除元素
//查询工资大于7000的
employees.stream().filter(e -> e.getSalary() > 7000).forEach(System.out::println);
System.out.println("---------------------");
//2. limit():截断流,使其元素不超过给定的数量
employees.stream().limit(3).forEach(System.out::println);
//3. skip(long n):跳过元素,放回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补。
employees.stream().skip(3).forEach(System.out::println);
//4. distinct():筛选,通过流生成元素的hashCode()和equals()去除重复元素
employees.add(new Employee(1010,"wwww",40,8000));
employees.add(new Employee(1010,"wwww",40,8000));
employees.add(new Employee(1010,"wwww",40,8000));
employees.add(new Employee(1010,"wwww",40,8000));
employees.stream().distinct().forEach(System.out::println);
}
}
4.2.2.3 排序
/**
* 排序
*/
public void test5(){
//sorted()--自然排序
List<Integer> list = Arrays.asList(12, 43, 6, 5, 85, 0, 6, 76);
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> employees1 = EmployeeData.getEmployees();
employees1.stream()
.sorted((e1,e2)->{
int compare = Integer.compare(e1.getAge(), e2.getAge());
if(compare!=0){
return compare;
}else {
return Double.compare(e1.getSalary(),e2.getSalary());
}
})
.forEach(System.out::println);
}
4.2.3 终止操作
import com.java8.methodReferences.Employee;
import com.java8.methodReferences.EmployeeData;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author LanceQ
* @date 2021年11月20日 18:55
*
* stream的终止操作
*/
public class StreamApiTest2 {
public static void main(String[] args) {
//test1();
//test2();
test3();
}
/**
* 收集:collect(Collector c),
* 将流转换为其他新生。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
*
* collects实用类提供了很多的静态方法,可以方便地创建常用收集器实例
*/
private static void test3() {
List<Employee> employees = EmployeeData.getEmployees();
List<Employee> collect = employees.stream()
.filter(employee -> employee.getSalary() > 6000)
.collect(Collectors.toList());
collect.forEach(System.out::println);
System.out.println("-----------------------");
//set无序
Set<Employee> collect1 = employees.stream()
.filter(employee -> employee.getSalary() > 6000)
.collect(Collectors.toSet());
collect1.forEach(System.out::println);
}
/**
* 归约
*/
public static void test2(){
List<Employee> employees = EmployeeData.getEmployees();
//reduce(T identity,BinaryOperator):可以将流中的元素反复结合起来,
// 得到一个只。返回
//求和
List<Integer> list= Arrays.asList(1,2,3,4,5,6,7,8,9);
//前面一个是初始值
Integer sum = list.stream().reduce(0, Integer::sum);
System.out.println(sum);
//reduce(BinaryOperator):可以将流中元素反复结合,得到一个值,返回Optional<T>
Optional<Double> reduce = employees.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
//形参两个,返回一个
Optional<Double> reduce1 = employees.stream()
.map(Employee::getSalary)
.reduce((d1,d2)->d1+d2);
System.out.println(reduce);
}
/**
* 匹配与查找
*/
public static void test1(){
List<Employee> employees = EmployeeData.getEmployees();
//allMath(Predicate p)检查是否匹配所有元素
//查询employees里面的元素的年龄是否都大于18岁
boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
System.out.println(allMatch);
//anyMatch(Predicate p):检查是否至少匹配一个元素
//查询employees中是否存在员工的工资大于10000
boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
System.out.println(anyMatch);
//noneMatch(Predicate p):检查是否没有匹配的元素
//是否不存在员工姓“雷”
boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
System.out.println(noneMatch);
//findFirst:返回第一个元素
Optional<Employee> first = employees.stream().findFirst();
System.out.println(first);
//findAny:返回当前流中的任意元素(要并行流)(对半的)
Optional<Employee> any = employees.parallelStream().findAny();
System.out.println(any);
//count--返回流中元素的总个数
long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
System.out.println(count);
//max:返回最大值
Optional<Double> max = employees.stream()
.map(e -> e.getSalary())
.max(Double::compareTo);
System.out.println(max);
//min:返回最小值
Optional<Employee> employee = employees.stream()
.min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(employee);
//forEach(consumer c):内部迭代(使用Collection接口需要用户去做迭代,称为外部迭代。
// 相反,Stream API使用内部迭代--->他帮你把迭代做了)
employees.stream().forEach(System.out::println);
//使用集合的遍历操作
employees.forEach(System.out::println);
}
}
5 Optional类
import java.util.Optional;
/**
* @author LanceQ
* @date 2021年11月21日 12:57
* Optional类:为了在程序中避免出现空指针异常而创建的
*
* T get():如果调用对象包含值,返回该值,否则抛异常
*/
public class OptionalTest {
public static void main(String[] args) {
// test();
test1();
}
private static void test1() {
OptionalTest optionalTest = new OptionalTest();
// Boy boy = new Boy();
// String girlName = optionalTest.getGirlName(boy);
// System.out.println(girlName);
//一开始就为空
Boy boy1=null;
//里面为空
boy1=new Boy();
//正常
boy1=new Boy(new Girl("qqq"));
String girlName2 = optionalTest.getGirlName2(boy1);
System.out.println(girlName2);
}
//空指针
public String getGirlName(Boy boy) {
return boy.getGirl().getName();
}
//优化
public String getGirlName1(Boy boy) {
if(boy!=null){
Girl girl = boy.getGirl();
if(girl!=null){
return girl.getName();
}
}
return null;
}
//使用Optional类的getGirlName()
public String getGirlName2(Boy boy) {
Optional<Boy> boyOptional = Optional.ofNullable(boy);
//orElse(T t1):如果当前的Optional内部封装的t非空的,则返回内部的t,
//如果内部的t空的,则返回orElse()方法中的参数t1
Boy b = boyOptional.orElse(new Boy(new Girl("嘤嘤嘤")));
Girl girl = b.getGirl();
Optional<Girl> girlOptional = Optional.ofNullable(girl);
Girl girl1 = girlOptional.orElse(new Girl("呜呜呜·"));
return girl1.getName();
}
/**
* Optional.of(T t):创建一个Optional实例,t必须非空
* Optional.empty():创建一个空的Optional实例
* Optional.ofNullable(T t):t可以为null
*/
private static void test() {
Girl girl = new Girl();
//of(保证t是非空的)
Optional.of(girl);
Girl girl1 = new Girl();
Optional<Girl> g = Optional.ofNullable(girl1);
System.out.println(g);
girl1=null;
//Optional.ofNullable(T t):t可以为null
g = Optional.ofNullable(girl1);
System.out.println(g);
}
}
参考:视频