标签: method-reference

为什么两个方法引用被编译到两个不同的地址?

我两次引用相同的方法,但引用不同。看这个例子:

import java.util.function.Consumer;

public class MethodRefTest {
    public static void main(String[] args) {
        new MethodRefTest();
    }

    public MethodRefTest() {
        Consumer<Integer> a = this::method;
        System.out.println(a);
        Consumer<Integer> b = this::method;
        System.out.println(b);
    }

    public void method(Integer value) {

    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

MethodRefTest$$Lambda$1/250421012@4c873330
MethodRefTest$$Lambda$2/295530567@776ec8df
Run Code Online (Sandbox Code Playgroud)

方法引用只不过是匿名类的语法糖吗?如果不是,我该怎么做才能始终获得相同的方法引用?(除了在字段中存储一次参考以供使用之外。)

(应用:我认为方法引用是观察者实现的一种更漂亮的方式。但是每次使用不同的引用,一旦添加观察者就不可能从可观察者中删除观察者。)

java functional-interface method-reference

5
推荐指数
1
解决办法
386
查看次数

将对返回值的方法的 Java 引用转换为返回“void”的方法

在这一点上,JLS 转换规则似乎相当复杂:将对返回某个值的方法的引用转换为接受相同参数类型但返回 的引用是否正确void?我认为这还可以,因为void它比任何类型都窄。

例如...

import java.util.function.Consumer;

public class MethodRefCaster {

  /** Operation accepting and returning Integer. */
  Integer fooOp(Integer x) {
    System.out.println(x);
    return x + 3;
  }

  /** Applier of given op accepting Integer, returning void. */
  void applyOpToBar(Consumer<Integer> op, int bar) {
    op.accept(bar);
  }

  public static void main(String [] args) {
    MethodRefCaster x = new MethodRefCaster();

    // Cast the method ref to make it fit.
    x.applyOpToBar((Consumer<Integer>) x::fooOp, 42);
  }
}
Run Code Online (Sandbox Code Playgroud)

如您所料,这将打印 42。但这是正确的Java吗?非常感谢。

java casting method-reference

5
推荐指数
0
解决办法
458
查看次数

如何解决 java 8 中的“Lambdas 应替换为方法引用”声纳问题?

public static Set<NurseViewPrescriptionWrapper> create(final Set<NurseViewPrescriptionDTO> nurseViewPrescriptionDTOs) {
  return nurseViewPrescriptionDTOs.stream()
      .map(new Function<NurseViewPrescriptionDTO, NurseViewPrescriptionWrapper>() {
        @Override
        public NurseViewPrescriptionWrapper apply(NurseViewPrescriptionDTO input) {
          return new NurseViewPrescriptionWrapper(input);
        }
      })
      .collect(Collectors.toSet());
}
Run Code Online (Sandbox Code Playgroud)

我将上面的代码转换为 java 8 lamda 函数,如下所示。

public static Set<NurseViewPrescriptionWrapper> create(final Set<NurseViewPrescriptionDTO> nurseViewPrescriptionDTOs) {
  return nurseViewPrescriptionDTOs.stream()
      .map(input -> new NurseViewPrescriptionWrapper(input))
      .collect(Collectors.toSet());
}
Run Code Online (Sandbox Code Playgroud)

现在,我收到声纳问题,例如Lambdas should be replaced with method references“->”这个符号。我该如何解决这个问题?

java lambda java-8 method-reference

5
推荐指数
1
解决办法
1566
查看次数

Java Lambda 表达式和对泛型方法的方法引用

我有一个功能界面

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;

@FunctionalInterface
public interface SubmitterCompletable extends Submitter {
    @Override
    <T> CompletableFuture<T> submit(Callable<T> task);
}
Run Code Online (Sandbox Code Playgroud)

和两个函数

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

public final class CompletableFutureUtils {
    public static <U> CompletableFuture<U> runAsync(Callable<U> callable) {
        // ...
    }

    public static <U> CompletableFuture<U> runAsync(Callable<U> callable, Executor executor) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我想SubmitterCompletable使用 lambda 表达式或方法引用从这些函数创建 s。第一个通过使用方法引用工作得很好。

SubmitterCompletable submitterCompletable = CompletableFutureUtils::runAsync;
Run Code Online (Sandbox Code Playgroud)

然而,对于第二个,我必须使用 lambda 表达式来传递 an Executor,但它不起作用。

Executor executor = /* ... */;
SubmitterCompletable submitterCompletable = c -> …
Run Code Online (Sandbox Code Playgroud)

java generics lambda functional-interface method-reference

5
推荐指数
1
解决办法
619
查看次数

Java 8中的方法引用是否具有具体类型,如果是,它是什么?

这个问题与另一个问题密切相关.但是,我觉得这个问题的公认答案并不是那么明确.

那么,什么是 Java中8的方法引用的类型?这里有一个演示如何将方法引用"强制转换"(解除?)到java.util.function.Function:

package java8.lambda;

import java.util.function.Function;

public class Question {
  public static final class Greeter {
    private final String salutation;

    public Greeter(final String salutation) {
      this.salutation = salutation;
    }

    public String makeGreetingFor(final String name) {
      return String.format("%s, %s!", salutation, name);
    }
  }

  public static void main(String[] args) {
    final Greeter helloGreeter = new Greeter("Hello");

    identity(helloGreeter::makeGreetingFor)
      .andThen(g -> "<<<" + g + ">>>")
      .apply("Joe");

    //Compilation error: Object is not a function interface
//    Function
// …
Run Code Online (Sandbox Code Playgroud)

java lambda functional-programming java-8 method-reference

4
推荐指数
3
解决办法
2040
查看次数

方法"引用特定类型的任意对象的实例方法"如何解析任意对象?

在甲骨文的Java 8文档定义了4种类型,你可以用它代替Lambda表达式方法引用的.我想要理解的是一种方法引用,描述为:"引用特定类型的任意对象的实例方法",写作为ContainingType::methodName.

我不确定我是否遗漏了某些内容,但对我而言似乎更像是:"引用功能接口的抽象方法的第一个参数,假设它是类型ContainingType".我试图提出这个'任意对象'是第二个参数的例子,但当然它不能编译.

是否有官方参考如何由编译器解决此对象?我的理解是正确的:

  1. 任意对象必须是功能接口的抽象方法的第一个参数.
  2. 方法引用的签名必须与功能接口的抽象方法的签名相同,不带第一个参数.

所以带抽象方法的功能接口A method(B b, C c, D d)只能传递实例方法引用x::methodImpl或B::methodImpl.我无法通过C::methodImpl例如,它将是C具有其签名的类的实例A methodImpl(B b, D d).

还有其他我缺少的案例,这可能是Oracle以这种模棱两可的方式写这个的原因吗?

java lambda java-8 method-reference

4
推荐指数
1
解决办法
1204
查看次数

Java unil BiFunction中的方法参考

我有问题在java(util)函数中传递方法引用作为参数.

我有两个功能

Function<Value, Output> f1 = (val) -> {
    Output o = new Output();
    o.setAAA(val);
    return o;
};

Function<Value, Output> f2 = (val) -> {
    Output o = new Output();
    o.setBBB(val);
    return o;
};
Run Code Online (Sandbox Code Playgroud)

我想将它们合并为一个应该看起来像的函数

BiFunction<MethodRefrence, Value, Output> f3 = (ref, val) -> {
    Output o = new Output();
    Output."use method based on method reference"(val);
    return o;
};
Run Code Online (Sandbox Code Playgroud)

我想用这个函数

f3.apply(Output::AAA, number);
Run Code Online (Sandbox Code Playgroud)

可能吗 ?我无法弄清楚正确的语法,如何制作这样的功能.

java java-8 method-reference

4
推荐指数
1
解决办法
166
查看次数

使用函数引用在Kotlin中重写Java代码发生SAM类型冲突

我有一个示例Java代码使用方法引用,我想重写为Kotlin.Java版本使用方法参考,解决方案简短明了.但另一方面,我不能在Kotlin中使用方法参考.我设法编写的唯一版本如下所示.似乎Function3 { s: String, b: Boolean, i: Int -> combine(s, b, i) }可以用更干净的方式编写(如果可能的方法参考将是完美的).

我是Kotlin的新手,所以我会感激任何线索.

Java的

import io.reactivex.Observable;

public class TestJava {

    Observable<String> strings() {
        return Observable.just("test");
    }

    Observable<Boolean> booleans() {
        return Observable.just(true);
    }

    Observable<Integer> integers() {
        return Observable.just(1);
    }

    void test() {
        Observable.combineLatest(strings(), booleans(), integers(),
                this::combine);
    }

    double combine(String s, boolean b, int i) {
        return 1.0;
    }
}
Run Code Online (Sandbox Code Playgroud)

科特林

import io.reactivex.Observable
import io.reactivex.functions.Function3

class TestKotlin {

    fun strings(): Observable<String> {
        return Observable.just("test")
    }

    fun booleans(): Observable<Boolean> { …
Run Code Online (Sandbox Code Playgroud)

java lambda kotlin method-reference rx-java2

4
推荐指数
1
解决办法
1863
查看次数

如何将函数引用传递给我的方法并使用它们?

我有一个工作方法,我想使用lambdas或函数引用更通用.也就是说,对于在我的方法中调用的一些方法,我想将它们指定为我的方法的参数.但是我无法理解它.

假设我有以下基本类结构

class B {}
class C {
    public Set<Integer> getIds() { ... }
    public void addB(B b) { ... }
}
Run Code Online (Sandbox Code Playgroud)

我有自己的工作方法

private void p1(Map<Integer, C> cs, Map<Integer, B> bs) {
    for (C c : cs.values()) {
        for (Integer id : c.getIds()) {
            if (bs.containsKey(id)) {
                c.addB(bs.get(id));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是所谓的p1(cs, bs);- 到目前为止一切顺利.

使其更通用的第一步是为getIds()方法提供lambda .我使用以下方法实现了:

private void p1(Map<Integer, C> cs, Map<Integer, B> bs, Function<C, Set<Integer>> f) {
    for (C c : cs.values()) {
        for …
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 method-reference

4
推荐指数
1
解决办法
87
查看次数

实现Predicate而不是boolean

当我读到评论时,我正在阅读一个不相关的帖子:任何时候我发现自己需要一个多行lambda,我将这些行移动到私有方法并传递方法引用而不是lambda.

我在问:实现这种行为的正确方法是什么?使用在注释中发布的布尔方法,还是使用谓词?


例如:让我们说我想检查是否Table可用,其中可用的手段isClean,isEmpty,hasChair.

class Table{
    public boolean hasChair(){...}
    public boolean isClean(){...}
    public boolean isEmpty(){...}
}
Run Code Online (Sandbox Code Playgroud)

我可以List<Table> tablesList = Arrays.asList(table1,table2,table3,table4);用两种方式为我的列表实现我的过滤测试:第一个用布尔值:

public boolean isUsable(){
    return hasChair() && isClean() && isEmpty();
}
Run Code Online (Sandbox Code Playgroud)

并使用它 tablesList.stream().filter(Table::isUsable)

第二种方式是谓词:

public Predicate<Table> isUsable(){
    return table -> table.isEmpty() && table.isClean() && table.hasChair();
}
Run Code Online (Sandbox Code Playgroud)

适用于 tablesList.stream().filter(isUsable())


哪个是正确的实施?为什么选择一个而不是其他?有什么大不同吗?

java predicate java-8 java-stream method-reference

4
推荐指数
2
解决办法
146
查看次数