🤹♂️Java Brains 강의🤹♂️
https://www.youtube.com/playlist?list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3
✨ Lambda vs. Interface Implementations
· Interface
public interface Greeting {
public void perform();
}
· Interface Implementation
public class GreetingImpl implements Greeting{
@Override
public void perform() {
System.out.println("Hello Java8");
}
}
· Main
public class Main {
public static void main(String[] args) {
// Interface Implementation 사용
GreetingImpl greeting = new GreetingImpl();
greeting.perform();
// Lambda 사용
// 이렇게 쓰려면 interface 가 only one method 이어야 함
Greeting GreetingFunction = () -> System.out.println("Hello Java8");
}
}
➡️ By calling the interface method on it, just as if it were as an instance of a class
✨ Type Inference
☑️ 컴파일러가 타입을 추론하는 것
public class Main {
public static void main(String[] args) {
printLambda(s -> s.length());
}
public static void printLambda(StringLengthLambda l) {
System.out.println(l.getLength("Hello Lambda"));
}
interface StringLengthLambda {
int getLength(String s);
}
}
✨ Functional Interface
☑️ an interface which has only one abstract method
☑️ use for declaring lambda types
☑️ @FunctionalInterface (Optional)
· Classic Case
public class Main {
public static void main(String[] args) {
// Anonymous inner class
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Printed inside Runnable");
}
});
myThread.run();
// Lambda 의 Functional Interface
Thread myLambdaThread = new Thread(() -> System.out.println("Printed inside Lambda Runnable"));
myLambdaThread.run();
}
}
➡️ Lambda behaves like the interface that it expects thread
➡️ Remember, this works because Runnable has a single method
The advantage of using an interface is we can use lambdas in place of all those anonymous inner classes and all the other methods signatures which accept the interface you don't have to rewrite them for the new function path
→ a huge advantage when it comes to backward compatibility
'Spring > JAVA' 카테고리의 다른 글
[Java8 Lambda] Exception Handling in Lambdas (try - catch) (0) | 2023.10.13 |
---|---|
[Java8 Lambda] Using Functional Interfaces (Predicate, Consumer) (0) | 2023.10.12 |
[Java8 Lambda] Lambda Expressions (0) | 2023.10.10 |
Java 제어문3 - 반복문 (+ 배열) (0) | 2023.10.06 |
Java 제어문2 - 조건문 (0) | 2023.10.05 |