1、Predicate/Consumer/Function/Supplier介绍

  1. Predicate boolean test(T t);
  2. Consumer accpet(T t);
  3. Function<T, R> R apply(T t);
  4. Supplier<T> T get();

以Predicate为例,引申出很多类似的Predicate,如IntPredicate、DoublePredicate、BiPredicate、LongPredicate。但是他们的用法都是差不多的。比较类似。

2、举例子:

  1. package com.cy.java8;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6. import java.util.function.*;
  7.  
  8. public class LambdaUsage {
  9.  
  10. private static List<Apple> filter(List<Apple> source, Predicate<Apple> predicate){
  11. List<Apple> result = new ArrayList<>();
  12. for(Apple a : source){
  13. if(predicate.test(a)){
  14. result.add(a);
  15. }
  16. }
  17. return result;
  18. }
  19.  
  20. //根据一个long类型的参数过滤
  21. private static List<Apple> filterByWeight(List<Apple> source, LongPredicate predicate){
  22. List<Apple> result = new ArrayList<>();
  23. for(Apple a : source){
  24. if(predicate.test(a.getWeight())){
  25. result.add(a);
  26. }
  27. }
  28. return result;
  29. }
  30.  
  31. //根据两个参数过滤
  32. private static List<Apple> filterByColorWeight(List<Apple> source, BiPredicate<String, Long> bipredicate){
  33. List<Apple> result = new ArrayList<>();
  34. for(Apple a : source){
  35. if(bipredicate.test(a.getColor(), a.getWeight())){
  36. result.add(a);
  37. }
  38. }
  39. return result;
  40. }
  41.  
  42. private static void simpleTestConsumer(List<Apple> source, Consumer<Apple> consumer){
  43. for(Apple a : source){
  44. consumer.accept(a);
  45. }
  46. }
  47.  
  48. private static String testFunction(Apple apple, Function<Apple, String> fun){
  49. return fun.apply(apple);
  50. }
  51.  
  52. public static void main(String[] args) {
  53. List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
  54. List<Apple> greenList = filter(list, apple -> apple.getColor().equals("green"));
  55. System.out.println(greenList);
  56.  
  57. System.out.println("-----------------------------");
  58. List<Apple> weightList = filterByWeight(list, weight -> weight>=150);
  59. System.out.println(weightList);
  60.  
  61. System.out.println("-----------------------------");
  62. List<Apple> result = filterByColorWeight(list, (color, weight) -> color.equals("red") && weight > 100);
  63. System.out.println(result);
  64.  
  65. System.out.println("-----------------------------");
  66. simpleTestConsumer(list, apple -> System.out.println("print apple's string method: " +apple));
  67.  
  68. System.out.println("-----------------------------");
  69. String color = testFunction(new Apple("yellow", 10), apple -> apple.getColor());
  70. System.out.println(color);
  71.  
  72. System.out.println("-----------------------------");
  73. Supplier<String> supplier = String::new;
  74. System.out.println(supplier.get().getClass());
  75. }
  76.  
  77. }

打印结果:

  1. [Apple(color=green, weight=120)]
  2. -----------------------------
  3. [Apple(color=red, weight=150)]
  4. -----------------------------
  5. [Apple(color=red, weight=150)]
  6. -----------------------------
  7. print apple's string method: Apple(color=green, weight=120)
  8. print apple's string method: Apple(color=red, weight=150)
  9. -----------------------------
  10. yellow
  11. -----------------------------
  12. class java.lang.String

3、方法推导解析      

什么情况下允许方法推导的方式来写呢?
1.可以通过一个类的静态方法,比如Integer::parseInt
2.可以通过一个类的成员方法。
3.可以通过一个类的实例的方法。
4.可以通过构造函数的推导。

举例子:

  1. package com.cy.java8;
  2.  
  3. import lombok.Data;
  4.  
  5. @Data
  6. public class ComplexApple {
  7. private String color;
  8. private long weight;
  9. private String name;
  10.  
  11. public ComplexApple(String color, long weight, String name) {
  12. this.color = color;
  13. this.weight = weight;
  14. this.name = name;
  15. }
  16. }
  1. package com.cy.java8;
  2.  
  3. @FunctionalInterface
  4. public interface ThreeParamFuntion<T, U, K, R> {
  5.  
  6. R apply(T t, U u, K k);
  7. }
  1. package com.cy.java8;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Comparator;
  5. import java.util.List;
  6. import java.util.function.BiFunction;
  7. import java.util.function.Consumer;
  8. import java.util.function.Function;
  9. import java.util.function.Supplier;
  10. import java.util.stream.Stream;
  11.  
  12. public class MethodReference {
  13.  
  14. public static void main(String[] args) {
  15. /*Consumer<String> consumer = s -> System.out.println(s);
  16. useConsumer(consumer,"hello alex");*/
  17.  
  18. useConsumer(s -> System.out.println(s),"hello alex");
  19. useConsumer(System.out::println, "hello today");
  20.  
  21. List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("abc", 100), new Apple("red", 150));
  22. System.out.println(list);
  23. list.sort((a1, a2) -> a1.getColor().compareTo(a2.getColor()));
  24. System.out.println(list);
  25.  
  26. //比如循环输出apple信息
  27. list.stream().forEach(apple -> System.out.println(apple));
  28.  
  29. //可以改成成如下
  30. System.out.println("-----------------------------------------");
  31. list.stream().forEach(System.out::println);
  32. System.out.println("-----------------------------------------");
  33.  
  34. //方法推导,通过一个类的静态方法
  35. Function<String, Integer> funtion = Integer::parseInt;
  36. int result = funtion.apply("123");
  37. System.out.println(result);
  38.  
  39. //方法推导,通过一个类的成员方法
  40. BiFunction<String, Integer, Character> f1 = String::charAt;
  41. System.out.println(f1.apply("index", 0));
  42.  
  43. //方法推导,通过一个类的实例的方法
  44. String s = new String("index");
  45. Function<Integer, Character> f2 = s::charAt;
  46. System.out.println(f2.apply(1));
  47.  
  48. //通过构造函数的推导
  49. Supplier<String> s1 = String::new;
  50. System.out.println(s1.get().getClass().getSimpleName());
  51.  
  52. BiFunction<String, Long, Apple> biFunction = Apple::new;
  53. System.out.println(biFunction.apply("pink", 2L));
  54.  
  55. //三个参数的构造方法,ComplexApple::new,需要自己定义FunctionalInterface
  56. ThreeParamFuntion<String, Long, String, ComplexApple> threeParamFuntion = ComplexApple::new;
  57. System.out.println(threeParamFuntion.apply("black", 1L, "blackApple"));
  58.  
  59. //再次看下上面list的排序的另一种方法
  60. List<Apple> list2 = Arrays.asList(new Apple("green", 120), new Apple("abc", 100), new Apple("red", 150));
  61. list2.sort(Comparator.comparing(Apple::getColor));
  62. System.out.println(list2);
  63. }
  64.  
  65. private static <T> void useConsumer(Consumer<T> consumer, T t){
  66. consumer.accept(t);
  67. consumer.accept(t);
  68. }
  69.  
  70. }

打印如下:

  1. hello alex
  2. hello alex
  3. hello today
  4. hello today
  5. [Apple(color=green, weight=120), Apple(color=abc, weight=100), Apple(color=red, weight=150)]
  6. [Apple(color=abc, weight=100), Apple(color=green, weight=120), Apple(color=red, weight=150)]
  7. Apple(color=abc, weight=100)
  8. Apple(color=green, weight=120)
  9. Apple(color=red, weight=150)
  10. -----------------------------------------
  11. Apple(color=abc, weight=100)
  12. Apple(color=green, weight=120)
  13. Apple(color=red, weight=150)
  14. -----------------------------------------
  15. 123
  16. i
  17. n
  18. String
  19. Apple(color=pink, weight=2)
  20. ComplexApple(color=black, weight=1, name=blackApple)
  21. [Apple(color=abc, weight=100), Apple(color=green, weight=120), Apple(color=red, weight=150)]

lambda表达式使用解析的更多相关文章

  1. Lambda表达式树解析(下)

    概述 前面章节,总结了Lambda树的构建,那么怎么解析Lambda表达式树那?Lambda表达式是一种委托构造而成,如果能够清晰的解析Lambda表达式树,那么就能够理解Lambda表达式要传递的正 ...

  2. Lambda表达式树解析(下)包含自定义的provider和查询

    概述 前面章节,总结了Lambda树的构建,那么怎么解析Lambda表达式树那?Lambda表达式是一种委托构造而成,如果能够清晰的解析Lambda表达式树,那么就能够理解Lambda表达式要传递的正 ...

  3. 今夜我懂了Lambda表达式_解析

    现在时间午夜十一点~ 此刻的我血脉喷张,异常兴奋:因为专注得学习了一把java,在深入集合的过程中发现好多套路配合Lambda表达式真的是搜椅子,so开了个分支,决定从"只认得", ...

  4. Python 中Lambda 表达式 实例解析

    Lambda 表达式 lambda表达式是一种简洁格式的函数.该表达式不是正常的函数结构,而是属于表达式的类型.而且它可以调用其它函数. 1.基本格式: lambda 参数,参数...:函数功能代码 ...

  5. C++11 Lambda表达式简单解析

    C++11 新增了非常多特性,lambda 表达式是当中之中的一个.假设你想了解的 C++11 完整特性, 建议去http://www.open-std.org/看看新标准! 非常多语言都提供了 la ...

  6. SqlHelper简单实现(通过Expression和反射)5.Lambda表达式解析类

    这个ExpressionHelper类,是整个SqlHelper中,最核心的一个类,主要功能就是将Lambda表达式转换为Sql语句.同时这个转换过程比较复杂,所以下面详细讲解一下思路和这个类的作用. ...

  7. python函数,lambda表达式,三目运算,列表解析,递归

    一.自定义函数 定义函数时,函数体不执行:只有在调用函数时,函数体才执行.函数的结构: 1. def 2. 函数名 3. 函数体 def func_name(): 函数体 4. 返回值 如果没有声明返 ...

  8. 解析 Lambda 表达式

    我们先创建一个表达式树: Expression<Func<int, int, int>> expression = (a,b) => a + b; 我们的例子是一个Exp ...

  9. 将Lambda表达式作为参数传递并解析-在构造函数参数列表中使用Lambda表达式

    public class DemoClass { /// <summary> /// 通过Lambda表达式,在构造函数中赋初始值 /// </summary> /// < ...

随机推荐

  1. iOS App沙盒目录结构

    转自:http://blog.csdn.net/wzzvictory/article/details/18269713 出于安全考虑,iOS系统的沙盒机制规定每个应用都只能访问当前沙盒目录下面的文件( ...

  2. Redis启动方式

    一.前端启动 直接运行bin/redis-server将以前端模式启动.[bin目录是在/usr/local/redis/bin] # ./redis-server 启动缺点: ssh命令窗口关闭则r ...

  3. PHP的htmlspecialchars、strip_tags、addslashes

    PHP的htmlspecialchars.strip_tags.addslashes是网页程序开发中常见的函数,今天就来详细讲述这些函数的用法: 1.函数strip_tags:去掉 HTML 及 PH ...

  4. Delphi 循环语句和程序的循环结构

  5. mysql5.7二进制包进行多实例安装

    一.需求 在一台服务器上安装mysql5.7,并且部署两个实例:3306用于本机主库,3307用于其他MYSQL服务器的从库 二.下载mysql二进制包 [root@push-- src]# -lin ...

  6. 22_4mybatis——动态SQL

    1.创建maven工程并导入坐标 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE confi ...

  7. [NoSql注入] MongoDB学习

    0x00 安装 下载:http://dl.mongodb.org/dl/win32/x86_64 安装:http://www.runoob.com/mongodb/mongodb-window-ins ...

  8. java知识

    DiskFileUploadhttps://blog.csdn.net/FightingITPanda/article/details/79742631 import java.util.ArrayL ...

  9. [Python模块]Windows环境安装PyV8并执行js语句

    安装这个玩意儿真挺坑的,pip直接安装失败,windows的py库压根搜不到.. 搜索良多解决办法终于找到了,在这里贴出来,主要是把这个库下载下来再安装,但它的下载地址HERE位于外面的世界(你懂得) ...

  10. 如果该虚拟机未在使用,请按“获取所有权(T)”按钮获取它的所有权。否则,请按“取消(C)”按钮以防损坏

    ---恢复内容开始--- 解决办法:打开放此台Vmware虚拟机虚拟磁盘文件及配置文件存放的位置(也就是弹出提示窗口上的路径),删除后缀为.lck的文件夹 ---恢复内容结束---