有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 8+中的lambda是流中唯一允许的单参数方法引用

在Java 8中的Stream中,您只能使用带单个参数的方法引用(如果您不允许用方法调用包装方法引用),这是真的吗

我这样假设是因为在流中,您随时都在处理单个项目

因此:

  • Something::new(必须引用单个参数构造函数)
  • this::doSomething(必须采用单个参数)
  • Something::doSomething (必须使用单个arg)

。。。在Stream中使用时。这条规则总是正确的吗


共 (3) 个答案

  1. # 1 楼答案

    再加上answer from Eran,你可能会找到一个更容易理解的真实例子

    让我们假设我们有一个方法,它添加了Integer iintValueLong l作为String s表示返回。这看起来像:

    String convertToStringAfterAddingValues(Long l, Integer i) {
        return String.valueOf(l.intValue() + i);
    }
    

    FunctionalInterface的世界中,这可以表示为BiFunction的匿名类:

    BiFunction<Long, Integer, String> biFunctionAnonymous = new BiFunction<Long, Integer, String>() {
        @Override
        public String apply(Long l, Integer i) {
            return String.valueOf(l.intValue() + i);
        }
    };
    

    在lambda世界中,可以用以下形式表示:

    BiFunction<Long, Integer, String> biFunctLambda = (l, i) -> String.valueOf(l.intValue() + i);
    

    也可以使用方法引用来表示,方法所在的类的对象为:

    BiFunction<Long, Integer, String> biFunctMethodReference = <YourClassInstance>::convertToStringAfterAddingValues;
    
  2. # 2 楼答案

    不,不是。一些Stream方法采用函数接口,该接口具有一个具有多个参数的方法

    例如,Streamsorted(Stream<T> Comparator<? super T> comparator)方法采用Comparator,其方法有两个参数

    下面是一个使用具有两个参数的方法的方法引用String::compareTo的示例:

    System.out.println(Stream.of("a","d","c").sorted(String::compareTo).collect(Collectors.toList()));
    

    StreamOptional<T> max(Comparator<? super T> comparator)方法是另一个类似的例子

  3. # 3 楼答案

    有四种方法参考:

    • 静态方法的方法引用,即

      Class::staticMethod>(args) -> Class.staticMethod(args)

    • 对特定类型对象的实例方法的方法引用。i、 e

      ObjectType::instanceMethod>(obj, args) -> obj.instanceMethod(args)

    • 对现有对象实例方法的方法引用,即

      obj::instanceMethod>(args) -> obj.instanceMethod(args)

    • 对构造函数的方法引用,即

      ClassName::new>(args) -> new ClassName(args)

    正如您在第二个示例中看到的,一个给定的方法可以接受两个参数,但仍然可以转换为方法引用,对于调用sortedminmax等的情况也是如此。。一条小溪

    上面的例子要归功于Java 8 Method Reference: How to Use it