//原始方法
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("长安欢迎您");
}
};
r1.run();
System.out.println("+++++++++++++++++++++++++|");
//lambda表达式
Runnable r2 = () -> System.out.println("长安欢迎您");
r2.run();
Comparator<Integer> c1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1,o2);
}
};
int compare1 = c1.compare(8,16);
System.out.println(compare1);
System.out.println("+++++++++++++++++++++++");
//Lambda表达式的写法
Comparator<Integer> c2 = (o1,o2) -> Integer.compare(o1,o2);
int compare2 = c2.compare(28,35);
System.out.println(compare2);
System.out.println("+++++++++++++++++++++++++++");
//方法引用
Comparator<Integer> c3 = Integer :: compare;
int compare3 = c3.compare(28,35);
System.out.println(compare3);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QeRUyL91-1653371879185)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20220125123853336.png)]
//语法格式一:无参,无返回值
@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 test5(){
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 test6(){
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 test7(){
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));
}
/* java内置的4大核心函数式接口
* 消费型接口 Consumer void accept(T t)
* 供给型接口 Supplier T get()
* 函数型接口 Function R apply(T t)
* 断定型接口 Predicate boolean test(T t)
*/
public class LambdaTest2 {
public void happyTime(double money, Consumer<Double> con) {
con.accept(money);
}
@Test
public void test(){
happyTime(500, 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);
}
}
// 情况一:对象 :: 实例方法
//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("beijing");
}
//Supplier中的T get()
//Employee中的String getName()
@Test
public void test2() {
Employee emp = new Employee(1004,"tom",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());
}
// 情况二:类 :: 静态方法
//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));
}
// 情况三:类 :: 实例方法(有难度)
// Comparator中的int comapre(T t1,T t2)
// String中的int t1.compareTo(t2) 虽然形参列表不一致,但第一个参数t1是方法的调用者,则也能这么用。
@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("ABC","ABC"));
System.out.println("++++++++++++++++++++");
BiPredicate<String,String> pre2 = String :: equals;
System.out.println(pre2.test("ABC","ABC"));
}
格式:ClassName::new
构造器引用和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。抽象方法的返回值类型即为构造器所属的类的类型
数组引用可以把数组看做是一个特殊的类,则写法与构造器引用一致。数组类型[]::new
//构造器引用
//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(1001);
System.out.println(employee);
System.out.println("+++++++++++++++++++");
Function<Integer, Employee> f2 = Employee::new;
Employee employee1 = f2.apply(1002);
System.out.println(employee1);
}
//数组引用
//Function中的R apply(T t)
@Test
public void test4() {
Function<Integer, String[]> f1 = length -> new String[length];
String[] arr1 = f1.apply(5);
System.out.println(Arrays.toString(arr1));
System.out.println("+++++++++++++++++++");
Function<Integer, String[]> f2 = String[]::new;
String[] arr2 = f2.apply(10);
System.out.println(Arrays.toString(arr2));
}
Stream 是Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用SQL 执行的数据库查询。也可以使用Stream API 来并行执行操作。简言之,Stream API 提供了一种高效且易于使用的处理数据的方式。
Stream关注的是对数据的运算,与CPU打交道; 集合关注的是数据的存储,与内存打交道
Stream 执行流程
说明:
//创建 Stream方式一:通过集合
List<Employee> employees = EmployeeData.getEmployees();
//default Stream stream() : 返回一个顺序流
Stream<Employee> stream = employees.stream();
//default Stream parallelStream() : 返回一个并行流
Stream<Employee> parallelStream = employees.parallelStream();
//创建 Stream方式二:通过数组
int[] arr = new int[]{1,2,3,4,5,6};
//调用Arrays类的static Stream 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()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
//创建 Stream方式四:创建无限流
//迭代
//public static Stream iterate(final T seed, final UnaryOperator f)
//遍历前10个偶数
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
//生成
//public static Stream generate(Supplier s)
Stream.generate(Math::random).limit(10).forEach(System.out::println)
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);
System.out.println("+++++++++++++++++++++++");
//limit(n)——截断流,使其元素不超过给定数量。
list.stream().limit(3).forEach(System.out::println);
System.out.println("+++++++++++++++++++++++");
//skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
list.stream().skip(3).forEach(System.out::println);
System.out.println("+++++++++++++++++++++++");
//distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
list.add(new Employee(1010,"Tom",42,8500));
list.add(new Employee(1010,"Tom",41,8200));
list.add(new Employee(1010,"Tom",28,6000));
list.add(new Employee(1010,"Tom",39,7800));
list.add(new Employee(1010,"Tom",40,8000));
//System.out.println(list);
list.stream().distinct().forEach(System.out::println);
//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);
System.out.println();
//flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
Stream<Character> characterStream = list.stream().flatMap(StreamAPITest2::fromStringToStream);
characterStream.forEach(System.out::println);
sorted() 产生一个新流,其中按自然顺序排序
sorted(Comparator com) 产生一个新流,其中按比较器顺序排序
//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 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);
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() > 10000);
System.out.println(anyMatch);
//noneMatch(Predicate p)——检查是否没有匹配的元素。
//练习:是否存在员工姓“马”
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);
//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);
//reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
//练习1:计算1-10的自然数的和
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Integer sum = list.stream().reduce(0, Integer::sum);
System.out.println(sum);
//reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional
//练习2:计算公司所有员工工资的总和
List<Employee> employees = EmployeeData.getEmployees();
Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
//Optional sumMoney = salaryStream.reduce(Double::sum);
Optional<Double> sumMoney = salaryStream.reduce((d1,d2) -> d1 + d2);
System.out.println(sumMoney.get());
//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);
System.out.println("++++++++++++++++++");
Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);
Optional类:为了在程序中避免出现空指针异常而创建的。
Optional.of(T t)
: 创建一个Optional 实例,t必须非空;Optional.empty()
: 创建一个空的Optional 实例Optional.ofNullable(T t
):t可以为nullT orElse(T other)
:如果有值则将其返回,否则返回指定的other对象。 //优化以后的getGirlName():
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);
//此时的boy1一定非空
//orElse(T t1):如果单前的Optional内部封装的t是非空的,则返回内部的t.
//如果内部的t是空的,则返回orElse()方法中的参数t1.
Boy boy1 = boyOptional.orElse(new Boy(new Girl("Jerry")));
Girl girl = boy1.getGirl();
Optional<Girl> girlOptional = Optional.ofNullable(girl);
//girl1一定非空
Girl girl1 = girlOptional.orElse(new Girl("Mille"));
return girl1.getName();
}
@Test
public void test5(){
Boy boy = null;
// String girlName = getGirlName2(boy);// Jerry
boy = new Boy();
// String girlName = getGirlName2(boy);// Mille
boy = new Boy(new Girl("Tommy"));
String girlName = getGirlName2(boy);// Tommy
System.out.println(girlName);
}