在Java 8中将匿名内部方法转换为Lambda

时间:2017-04-25 22:31:29

标签: java lambda java-8

如何使用Java 8将以下代码(特别是public void run()方法)转换为lambda?

Thread t1 = new Thread(new Runnable() -> {

    for (int i = 0; i < 10; i++) {
        System.out.println("Hello " + i);
        try {
            Thread.sleep(100);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    };

);

尝试:

  "com.lmax" % "disruptor" % "3.3.5",
  "org.apache.logging.log4j" % "log4j-api" % "2.8.2",
  "org.apache.logging.log4j" % "log4j-core" % "2.8.2",
  "org.apache.logging.log4j" %% "log4j-api-scala" % "2.8.2"

但Eclipse不断抛出错误......

2 个答案:

答案 0 :(得分:8)

只需删除new Runnable

即可
Thread t1 = new Thread(() -> { /* body */ });

您可能需要考虑将该主体拉出为“真实”方法,并改为使用方法引用:

static void doSomething() { /* body */ }

public static void main(String[] args) {
  Thread t1 = new Thread(SampleApp::doSomething);
}

大lambda体不是特别易读。

答案 1 :(得分:0)

嗨,如果你想要内联你可以这样做

    final Thread t1 = new Thread(()->{
        for (int i = 0; i < 10; i++) {
            System.out.println("Hello " + i);
            try { Thread.sleep(100); }
            catch (final InterruptedException e) {
                e.printStackTrace();
            }
        }
    });