Java 8中函数式接口的使用

7
这是一个关于Java 8中::(双冒号)操作符的后续问题,它允许您使用::操作符引用方法。
我是否可以提供一些自定义的函数式接口,并使用::操作符进行使用?如何实现?
3个回答

12

“我能否提供一些自定义的函数式接口,然后使用::操作符进行使用?怎么做呢?”

是可以的,而且比你想象的还要简单:只需创建一个拥有恰好一个方法的接口即可。甚至不需要@FunctionalInterface注解;这个注解只是用于记录你的意图,并帮助在编译时检测类似于@Override的错误。

所以,也许你在Java 8之前的项目中已经创建了这样的接口……

class Foo {
    // nothing new:
    public interface FooFactory {
        Foo createFoo();
    }
    // new in Java 8:
    public static final FooFactory DEFAULT_FACTORY = Foo::new;
}

4
如何提供自定义的函数式接口实现以使用::运算符
public class TestingLambda {

    public static void main(String[] args) {
        int value1 = method(TestingLambda::customMethod1);
        int value2 = method(TestingLambda::customMethod2);

        System.out.println("Value from customMethod1: " + value1);
        System.out.println("Value from customMethod2: " + value2);
    } 

    public static int customMethod1(int arg){
        return arg + 1;
    }

    public static int customMethod2(int arg){
        return arg + 2;
    }

    public static int method(MyCustomInterface ob){
        return ob.apply(1);
    }

    @FunctionalInterface
    interface MyCustomInterface{
        int apply(int arg);
    }
}

阶段1:创建自定义功能接口

我已经创建了自己的FunctionalInterface,名为MyCustomInterface,在Java 8中,您必须使用@FunctionalInterface注释声明接口为功能接口。现在它有一个单一的方法,使用int作为参数并返回int

阶段2:创建一些符合该签名的方法

创建了两个方法customMethod1customMethod2,它们符合该自定义接口的签名。

阶段3:创建一个以函数接口(MyCustomInterface)为参数的方法

methodMyCustomInterface作为参数。

现在您准备好了。

阶段4:使用

在主方法中,我使用了method,并将其传递给我自定义方法的实现。

method(TestingLambda::customMethod1); 

1

给你

import java.util.Arrays;

class Sort {
    public int compareByLength(String s1, String s2) {
        return (s1.length() - s2.length());
    }
}

public class LambdaReferenceExample1 {
    public static void main(String[] javalatteLambda) {
        String[] str = {"one", "two", "3", "four", "five", "sixsix", 
            "sevennnnn", "eight"};
        Sort sort = new Sort();
        Arrays.sort(str, sort::compareByLength);

        for (String s : str) {
            System.out.println(s);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接