zoukankan      html  css  js  c++  java
  • java基础-匿名函数

    匿名函数

    ::操作符

    • A static method (ClassName::methName)
    • An instance method of a particular object (instanceRef::methName)
    • A super method of a particular object (super::methName)
    • An instance method of an arbitrary object of a particular type (ClassName::methName)
    • A class constructor reference (ClassName::new)
    • An array constructor reference (TypeName[]::new)
    1. 静态方法引用,如System.out::println
    2. 对象方法引用,如Person::getAge
    3. 构造方法引用,如ArrayList::new
    4. 数组构造器的引用,如String[]::new
    5. 超类方法的引用,如super::method

    BiConsumer

    @Test
    public void testBiConsumer (){
        BiConsumer<Person, String> biConsumerRef = Person::setName;
        BiConsumer<Person, String> biConsumer = (Person person, String name) -> person.setName(name);
        test(Person::setAge);
        test((Person a ,Integer b)->a.setAge(b));
    }
    public static  void  test(BiConsumer<Person,Integer> consumer){
        Person person = new Person("1", 28);
        consumer.accept(person,2);
        System.out.println(person);
    }
    

    Consumer

    @Test
    public void testObjectMethod() {
        List<String> list = Arrays.asList("aaaa", "bbbb", "cccc");
        //对象实例语法	instanceRef::methodName
        list.forEach(this::print);
        list.forEach(n-> System.out.println(n));
    }
    
    public void print(String content){
        System.out.println(content);
    }
    

    数组构造器

    @Test
    public void testArray (){
        IntFunction<int[]> arrayMaker = int[]::new;
        // creates an int[10]
        int[] array = arrayMaker.apply(10);
        array[9]=10;
        System.out.println(array[9]);
    }
    

    构造方法

    public class Example {
    
        private String name;
    
        Example(String name) {
            this.name = name;
        }
    
        public static void main(String[] args) {
            InterfaceExample com = Example::new;
            Example bean = com.create("hello world");
            System.out.println(bean.name);
        }
    
        interface InterfaceExample {
    
            Example create(String name);
        }
    }
    
    

    这里的用法可能觉得很奇怪。理解一点函数式接口与方法入参以及返回类型一样,就能将该方法赋值给该接口

    这里的Example::newExample create(String name)的入参以及返回值都一样,所以可以直接赋值

    InterfaceExample com = Example::new;
    

    资料

    官网说明

  • 相关阅读:
    基础知识漫谈(5):应用面向对象来分析“语言”
    【线段树】BZOJ2752: [HAOI2012]高速公路(road)
    【树状数组】BZOJ3132 上帝造题的七分钟
    【AC自动机】Lougu P3796
    【Splay】bzoj1500(听说此题多码上几遍就能不惧任何平衡树题)
    【fhq Treap】bzoj1500(听说此题多码上几遍就能不惧任何平衡树题)
    【可持久化线段树】POJ2104 查询区间第k小值
    【RMQ】洛谷P3379 RMQ求LCA
    【倍增】洛谷P3379 倍增求LCA
    【网络流】POJ1273 Drainage Ditches
  • 原文地址:https://www.cnblogs.com/froggengo/p/14665399.html
Copyright © 2011-2022 走看看