用Java中的Lambda返回值 [英] Return value by lambda in Java

查看:339
本文介绍了用Java中的Lambda返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我设法找到了我需要的所有答案,但这使我感到困惑.假设我们有示例代码:

Till now I manage to find all answers I need but this one confusing me. Let's say we have example code:

public class Animal {
   private String species;
   private boolean canHop;
   private boolean canSwim;
   public Animal(String speciesName, boolean hopper, boolean swimmer) {
     species = speciesName;
     canHop = hopper;
     canSwim = swimmer;
   }
  public boolean canHop() { return canHop; }
  public boolean canSwim() { return canSwim; }
  public String toString() { return species; }
}

public interface CheckAnimal {
   public boolean test(Animal a);
}

public class FindSameAnimals {
   private static void print(Animal animal, CheckAnimal trait) {
      if(trait.test(animal)){
         System.out.println(animal);
      }

   public static void main(String[] args) {
      print(new Animal("fish", false, true), a -> a.canHop());
   }
}

OCA学习指南(考试1Z0-808)这本书说这两行是等效的:

OCA Study Guide (Exam 1Z0-808) book says that these two lines are equivalent:

a -> a.canHop()
(Animal a) -> { return a.canHop(); }

这是否意味着在第一种情况下,Java在幕后将关键字 return 添加到代码中?

Does this mean that, behind the scenes, Java adds keyword return to code in the first case?

如果答案为是,那么下一个代码如何编译(想象其他所有内容都放在适当的位置):

If answer is YES then how next code compile (imagine everything else is in proper place):

static int counter = 0;
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> counter++));

如果我们知道 execute 和Runnable的 run 的签名是:

if we know that signatures for execute and Runnable's run are:

void execute(Runnable command)
void run()

如果答案为否",那么Java如何知道何时需要返回某些内容以及什么时候不返回?也许在

If answer is NO then how Java know when it need to return something and when not to? Maybe in

a -> a.canHop()

情况下,我们想忽略方法的 boolean 返回类型.

推荐答案

这是否意味着在第一种情况下,Java在幕后将关键字return添加到了代码中?

Does this mean that, behind the scenes, Java adds keyword return to code in the first case?

否,编译器会生成字节码,它可能会生成相同的字节码,但不会更改语法,然后再次编译.

No, The compiler generates byte code, and it might generate the same byte code but it doesn't change the syntax and then compile it again.

我们想忽略方法的布尔返回类型.

we wanted to ignore boolean return type of method.

它可以根据要考虑的功能接口忽略一个值.

It has the option of ignoring a value based on what functional interfaces it is considering.

a -> a.canHop()

可能是

(Animal a) -> { return a.canHop(); }

(Animal a) -> { a.canHop(); }

基于上下文,但是如果可能的话,它倾向于第一个.

based on context, however it favours the first if possible.

考虑ExecutorService.submit(Callable<T>)ExecutorService.submit(Runnable)

ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(() -> counter++); // has to be Runnable
es.submit(() -> counter++); // Callable<Integer> or Runnable?

保存返回类型,您可以看到它是Callable<Integer>

Saving the return type you can see it's a Callable<Integer>

final Future<Integer> submit = es.submit(() -> counter++);


尝试一下,这是一个更长的例子.


To try yourself, here is a longer example.

static int counter = 0;

public static void main(String[] args) throws ExecutionException, InterruptedException {
    ExecutorService es = Executors.newSingleThreadExecutor();

    // execute only takes Runnable
    es.execute(() -> counter++);

    // force the lambda to be Runnable
    final Future<?> submit = es.submit((Runnable) () -> counter++);
    System.out.println(submit.get());

    // returns a value so it's a Callable<Integer>
    final Future<Integer> submit2 = es.submit(() -> counter++);
    System.out.println(submit2.get());

    // returns nothing so it must be Runnable
    final Future<?> submit3 = es.submit(() -> System.out.println("counter: " + counter));
    System.out.println(submit3.get());

    es.shutdown();
}

打印

null
2
counter: 3
null

第一个submit取一个Runnable,因此Future.get()返回null

The first submit take a Runnable so Future.get() returns null

第二个submit默认为Callable,因此Future.get()返回2

The second submit defaults to being a Callable so Future.get() returns 2

第三个submit只能是void返回值,因此它必须是Runnable,因此Future.get()返回null

The third submit can only be a void return value so it must be a Runnable so Future.get() returns null

这篇关于用Java中的Lambda返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆