NipGeihou's blog NipGeihou's blog
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档

NipGeihou

我见青山多妩媚,料青山见我应如是
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档
  • 设计模式

  • 开发规范

  • 经验分享

  • 记录

  • 快速开始

  • 笔记

    • 多线程与并发

    • JDK

      • Stream
      • 「Java」Lambda表达式与函数式编程
        • 函数式接口
          • 内置接口
          • 消费型接口(1入参 无返回)
          • 供给型接口(无入参 有返回)
          • 函数式接口(2入参 有返回)
          • 断言型接口(1入参 布尔返回)
        • Lambda
          • 示例
          • 语法
          • 一行代码,无入参
          • 一行代码,有入参
          • 一行代码,一个参数
          • 多行代码,多个参数
          • 方法引用
          • 构造器引用
          • 数组引用
        • 参考资料
      • Javadoc
    • Java集合

    • Spring

    • JVM

    • Other

  • 面试题

  • 微服务

  • 踩过的坑

  • Java
  • 笔记
  • JDK
NipGeihou
2022-08-12
目录

「Java」Lambda表达式与函数式编程

# 函数式接口

只有一个方法的接口

package java.util.function;

@FunctionalInterface
public interface Function<T, R> {

    R apply(T t);
    
}

# 内置接口

# 消费型接口(1 入参 无返回)

    @FunctionalInterface
    public interface Consumer<T> {
    
      /**
       * 对给定参数执行此操作。
       *
       * @param t 入参
       */
      void accept(T t);
      
    }
    
    @Test
    public void consumerTest() {
      happy(1000, (money) -> {
          System.out.println("收到" + money + "元");
      });
    
    }
    
    public void happy(double money, Consumer<Double> consumer) {
      consumer.accept(money);
    }
    
    收到1000.0元
    
    // Make sure to add code blocks to your code group

    # 供给型接口(无入参 有返回)

      @FunctionalInterface
      public interface Supplier<T> {
      
        /**
         * 得到结果。
         *
         * @return 结果
         */
        T get();
      }
      
        @Test
        public void supplierTest() {
            List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
            numList.forEach(System.out::println);
        }
      
        /**
         * 获取指定个数的整数列表
         *
         * @param num
         * @param supplier
         * @return
         */
        public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < num; i++) {
                list.add(supplier.get());
            }
            return list;
        }
      
      56
      77
      85
      94
      39
      21
      24
      7
      69
      76
      
      // Make sure to add code blocks to your code group

      # 函数式接口(2 入参 有返回)

        @FunctionalInterface
        public interface Function<T, R> {
        
            /**
             * 将此函数应用于给定的参数。
             *
             * @param t 函数参数
             * @return 函数结果
             */
            R apply(T t);
        }
        
            @Test
            public void functionTest() {
                String newString = strHandler("     NipGeihou    ", (str) -> str.trim());
                System.out.println(newString);
            }
        
            /**
             * 字符串处理
             *
             * @param str
             * @param function
             * @return
             */
            public String strHandler(String str, Function<String, String> function) {
                return function.apply(str);
            }
        
        NipGeihou
        
        // Make sure to add code blocks to your code group

        # 断言型接口(1 入参 布尔返回)

          @FunctionalInterface
          public interface Predicate<T> {
          
              /**
               * 根据给定的参数计算这个断言。
               *
               * @param t the input argument
               * @return {@code true} 如果输入参数与断言匹配,
               * 否则 {@code false}
               */
              boolean test(T t);
          }
          
              @Test
              public void predicateTest() {
                  List<String> list = Arrays.asList("NipGeihou", "NipSiusiu", "WaiHiuzing", "a", "b", "c");
                  List<String> stringList = filterString(list, (str) -> str.length() > 3);
                  stringList.forEach(System.out::println);
              }
          
              /**
               * 将满足条件的数据放入集合中
               *
               * @param list
               * @param predicate
               * @return
               */
              public List<String> filterString(List<String> list, Predicate<String> predicate) {
                  List<String> newList = new ArrayList<>();
                  for (String str : list) {
                      if (predicate.test(str)) {
                          newList.add(str);
                      }
                  }
                  return newList;
              }
          
          NipGeihou
          NipSiusiu
          WaiHiuzing
          
          // Make sure to add code blocks to your code group

          # Lambda

          # 示例

            CompletableFuture.runAsync(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello");
                }
            });
            
            CompletableFuture.runAsync(() -> {
                System.out.println("hello");
            });
            
            // Make sure to add code blocks to your code group

            # 语法

            # 一行代码,无入参

            Runnable runnable = () -> System.out.println("hello");
            

            # 一行代码,有入参

            Consumer<String> consumer = (res) -> System.out.println(res);
            consumer.accept("hello");
            

            # 一行代码,一个参数

            入参括号可省略

            Consumer<String> consumer = res -> System.out.println(res);
            consumer.accept("hello");
            

            # 多行代码,多个参数

            Comparator<Integer> comparator = (o1, o2) -> {
                int res = o1 - o2;
                return res;
            };
            

            # 方法引用

            要求:调用方法与函数式接口方法入参、出参一致

            对象::实例方法名

              // Consumer<String> consumer = (x) -> System.out.println(x);
              Consumer<String> consumer = System.out::println;
              consumer.accept("hello");
              
              Student student = new Student("NipGeihou", 18);
              // Supplier<String> supplier = () -> student.getName();
              Supplier<String> supplier = student::getName;
              System.out.println(supplier.get());
              
              // Make sure to add code blocks to your code group

              类::静态方法名

                // Comparator<Integer> comparator = (o1, o2) -> Integer.compare(o1, o2);
                Comparator<Integer> comparator = Integer::compare;
                System.out.println(comparator.compare(1, 2));
                
                // Make sure to add code blocks to your code group

                类::实例方法名

                  // BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);
                  BiPredicate<String, String> biPredicate = String::equals;
                  System.out.println(biPredicate.test("NipGeihou", "NipGeihou"));
                  
                  // Make sure to add code blocks to your code group

                  # 构造器引用

                  类::new

                  // Supplier<Student> supplier = () -> new Student();
                  Supplier<Student> supplier = Student::new;
                  Student student = supplier.get();
                  System.out.println(student);
                  
                  // BiFunction<String, Integer, Student> biFunction = (name, age) -> new Student(name, age);
                  BiFunction<String, Integer, Student> biFunction = Student::new;
                  Student student2 = biFunction.apply("NipGeihou", 18);
                  System.out.println(student2);
                  

                  # 数组引用

                  类[]:new

                  // Function<Integer,String[]> function = (x) -> new String[x];
                  Function<Integer,String[]> function = String[]::new;
                  String[] strings = function.apply(10);
                  System.out.println(strings.length);
                  

                  # 参考资料

                  1. 尚硅谷_Java8 新特性_Lambda 基础语法_哔哩哔哩_bilibili (opens new window)
                  上次更新: 2022/12/31, 03:04:26
                  Stream
                  Javadoc

                  ← Stream Javadoc→

                  最近更新
                  01
                  Docker Swarm
                  04-18
                  02
                  安全隧道 - gost
                  04-17
                  03
                  Solana最佳实践
                  04-16
                  更多文章>
                  Theme by Vdoing | Copyright © 2018-2025 NipGeihou | 友情链接
                  • 跟随系统
                  • 浅色模式
                  • 深色模式
                  • 阅读模式