Lambda 표현식이란?
- 익명 메소드를 사용해서 간결한 인터페이스 인스턴스 생성하는 방법이다.
- FunctionalInterface 에서 사용가능하다.
- 간결하게 표현이 가능하다.
@FuncionalInterface
public interface MyRunnable {
void run();
}
public class Main{
public static void main(String[] args){
MyRunnable r1 = new MyRunnable(){
@Override
public void run(){
System.out.println("Hello"):
}
}.run();
//위와 동일한 표현임
//익명 메소드를 사용해서 표현하는 방법 : 람다 표현식
MyRunnable r2 = () -> System.out.println("Hello");
}
}
public class Main {
public static void main(String[] args) {
MySupplier s = () -> "Helllo World";
MyMapper m = (str) -> str.length();
MyConsumer c = i -> System.out.println(i);
MyRunnable r = () -> c.consume(m.map(s.supply()));
r.run();
}
}
메소드 레퍼런스
- 람다 표현식에서 입력되는 값을 변경없이 바로 사용하는 경우
- 최종으로 적용될 메소드의 레퍼런스를 지정해주는 표현 방식
- 입력값을 변경하지 말라는 표현의 방식
MyMapper m = String::length;
MyConsumer c = System.out::println;
들어오는 값을 전부 다 넣어서 우측 메소드를 수행하게한다.
람다식 응용
@FunctionalInterface
public interface MyConsumer<T> {
void consume(T t);
}
public class Main2 {
public static void main(String[] args) {
//new Main2().loop(10, System.out::println);
new Main2().filteredNumbers(30,
i -> i % 2 == 0.
System.out::println
);
}
void loop(int n, MyConsumer<Integer> consumer){
for(int i = 0; i < n; i++){
consumer.consume(i);
}
}
void filteredNumbers(int max, Predicate<Integer> p, Consumer<Integer> c) {
for (int i = 0; i < max; i++) {
if (p.test(i)). c.accept(i);
}
}
}
IDE에 alt + enter -> 개선 가능
'JAVA' 카테고리의 다른 글
[JAVA/개념] 11장 기본 API 클래스 (1) | 2023.07.08 |
---|---|
[JAVA/개념] 인터페이스 (0) | 2023.07.02 |
[JAVA/개념] 상속(extends) (0) | 2023.07.02 |
[JAVA/개념] 클래스 (0) | 2023.07.02 |
private, private static, private static final (0) | 2022.07.14 |