简体   繁体   English

如何通过 Java 中的参数传递方法引用?

[英]How To Pass A Method Reference With Parameter In Java?

I don't know the exact name for it (I'm guessing method-reference) but here is what I'm talking about.我不知道它的确切名称(我猜是方法参考),但这就是我所说的。 Let's say I want to take the square root of all doubles in a double array.假设我想取双精度数组中所有双精度的平方根。 Then, if the array is called arr , I can do this:然后,如果数组被称为arr ,我可以这样做:

Arrays.stream(arr).map(Math::sqrt). // ... box it and stuff

However, if I want to square each number in an int array, I'm thinking of using Math.pow(num, 2) as the method.但是,如果我想对 int 数组中的每个数字求平方,我正在考虑使用Math.pow(num, 2)作为方法。 However, Math.pow has a second parameter, but I know it will always be 2. So I'm thinking I can do something like this:但是, Math.pow有第二个参数,但我知道它永远是 2。所以我想我可以这样做:

Arrays.stream(arr).map(Math::pow(2)). // ... box it and stuff

But this results in an error.但这会导致错误。 What can I do?我能做些什么?

you may use lambda and send Math.pow(n,2)您可以使用 lambda 并发送 Math.pow(n,2)

like this:像这样:

Stream.of(1.1,1.2,1.3).map(n -> Math.pow(n,2))

You can use a simple lambda expression.您可以使用简单的 lambda 表达式。

Arrays.stream(arr).map(d -> Math.pow(d, 2));

There are 2 ways to implement this:有两种方法可以实现这一点:

  • First, use lambda expression:首先,使用 lambda 表达式:

     Arrays.stream(arr).map(num -> Math.pow(num, 2));
  • Second, (if you still want to invoke a method reference here, and to understand correctly how method reference works): write another method that call Math.pow():其次,(如果您仍然想在这里调用方法引用,并正确理解方法引用的工作原理):编写另一个调用 Math.pow() 的方法:

     Arrays.stream(arr).map(this::square); private double square(double num) { return Math.pow(num, 2); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM