Reputation: 5374
How can I convert the following code (specifically the public void run() method) into a lambda using Java 8?
public class SampleApp {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Hello " + i);
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
}
}
Tried:
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();
}
};
);
But Eclipse keeps throwing errors...
Upvotes: 1
Views: 651
Reputation: 45
import java.util.stream.IntStream;
public class SampleApp {
public static void main(String[] args) {
new Thread( ()-> {
IntStream.iterate(0, i -> i +1).limit(10).forEach(i->{
System.out.println("Hello " + i);
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
});
}).start();
}}
Upvotes: 0
Reputation: 870
Hi if you want it inline you can do this
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();
}
}
});
Upvotes: 0
Reputation: 140299
Simply remove the new Runnable
:
Thread t1 = new Thread(() -> { /* body */ });
You might want to consider pulling that body out into a "real" method, and using a method reference instead:
static void doSomething() { /* body */ }
public static void main(String[] args) {
Thread t1 = new Thread(SampleApp::doSomething);
}
Big lambda bodies are not especially readable.
Upvotes: 8