您现在的位置是:首页 > 文章详情

SpringBoot2.0响应式编程系列(二)-函数式编程和lambda表达式

日期:2018-06-07点击:507
img_51fde83c1b5a937292e518da32793ecb.png

img_620f042bf316f52b13520bc8cae88f08.png

img_3a9a44428418fb2249fc7730d7954a1d.png

函数接口

img_e95311335adda92504665e6c40d755f9.png

img_62640a0dd13f71392abe3ac7bfe884ee.png

img_7fad12a192a259aa9bedbee6a0a5f144.png

方法引用

package lambda;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.IntUnaryOperator;

class Dog {
   private String name = "哮天犬";

   /**
    * 默认10斤狗粮
    */
   private int food = 10;

   public Dog() {

   }

   /**
    * 带参数的构造函数
    * 
    * @param name
    */
   public Dog(String name) {
       this.name = name;
   }

   /**
    * 狗叫,静态方法
    * 
    * @param dog
    */
   public static void bark(Dog dog) {
       System.out.println(dog + "叫了");
   }

   /**
    * 吃狗粮 JDK
    * 
    * 默认会把当前实例传入到非静态方法,参数名为this,位置是第一个;
    * 
    * @param num
    * @return 还剩下多少斤
    */
   public int eat(int num) {
       System.out.println("吃了" + num + "斤狗粮");
       this.food -= num;
       return this.food;
   }

   @Override
   public String toString() {
       return this.name;
   }
}

/**
* @author shishusheng
*/
public class MethodRefrenceDemo {

   public static void main(String[] args) {
       Dog dog = new Dog();
       dog.eat(3);

       // 方法引用
       Consumer<String> consumer = System.out::println;
       consumer.accept("接受的数据");

       // 静态方法的方法引用
       Consumer<Dog> consumer2 = Dog::bark;
       consumer2.accept(dog);

       // 非静态方法,使用对象实例的方法引用
       // Function<Integer, Integer> function = dog::eat;
       // UnaryOperator<Integer> function = dog::eat;
       IntUnaryOperator function = dog::eat;
       
       // dog置空,不影响下面的函数执行,因为java 参数是传值
       dog = null;
       System.out.println("还剩下" + function.applyAsInt(2) + "斤");
       //
       // // 使用类名来方法引用
       // BiFunction<Dog, Integer, Integer> eatFunction = Dog::eat;
       // System.out.println("还剩下" + eatFunction.apply(dog, 2) + "斤");
       //
       // // 构造函数的方法引用
       // Supplier<Dog> supplier = Dog::new;
       // System.out.println("创建了新对象:" + supplier.get());
       //
       // // 带参数的构造函数的方法引用
       // Function<String, Dog> function2 = Dog::new;
       // System.out.println("创建了新对象:" + function2.apply("旺财"));

       // 测试java变量是传值还是穿引用
       List<String> list = new ArrayList<>();
       test(list);

       System.err.println(list);
   }

   private static void test(List<String> list) {
       list = null;
   }
}

类型推断

img_4d40c59288fba5e6699917f8d744e6db.png
image.png
原文链接:https://yq.aliyun.com/articles/635959
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章