zoukankan      html  css  js  c++  java
  • java8新特性-方法引用

    方法引用:当要传递给Lambda体的操作,已经有了实现方法,可以使用方法引用。

    方法引用与lambda表达式结合使用,可以进一步简化代码。

    1)实例方法引用:特定对象的实例方法

    2)对象方法引用:特定类型的任意对象的实例方法

    3)静态方法引用

    4)构造方法引用

    实例方法引用   对象::实例方法

    interface A{
        String say();
    }
    public class Test {
        public static void main(String[] args) {
            Apple apple = new Apple(23,"zhsan");
            A a=()->apple.getName();
            System.out.println(a.say());
            A a1=apple::getName;
            System.out.println(a1.say());
        }
    }
    

    静态方法引用

    public class Test {
        public static void main(String[] args) {
            Comparator<Integer> com =(x,y)->Integer.compare(x,y);
            System.out.println( com.compare(23,45));
            Comparator<Integer> comparator =Integer::compare;
            System.out.println(comparator.compare(23,45));
        }

    对象方法引用:

    public class Test {
        public static void main(String[] args) {
            //BiPredicate 接受参数,返回boolean
            BiPredicate<String,String> b=(x,y)->x.equals(y);
            System.out.println(b.test("2fdfg","43"));
            BiPredicate<String,String> b2=String::equals;
            System.out.println(b2.test("2fdfg","43"));
        }
    }
    

    构造方法引用:

    interface A{
        public Object fun();
    }
    public class Test {
        public static void main(String[] args) {
         A a=()->new Apple();
         A a1=Apple::new;
        }
  • 相关阅读:
    初涉线性基
    Codechef December Challenge 2018 Division 2
    【贪心】bzoj1592: [Usaco2008 Feb]Making the Grade 路面修整
    请求库之requests
    爬虫基本原理
    Flask-SQLAlchemy
    虚拟环境
    自定义验证规则以及中间件简单介绍
    Form组件归类
    分页与中间件
  • 原文地址:https://www.cnblogs.com/yxj808/p/14960128.html
Copyright © 2011-2022 走看看