1. 람다 표현식
- 행위 전달 표현식
- 메소드로 전달할 수 있는 익명 함수를 단순화한 것이라고 할 수 있다.
2. 람다식의 특징
익명
함수
전달
간결성
3. 람다식의 장점
코드를 간결하게 만들 수 있고, 식에 개발자의 의도가 명확히 드러나 가독성이 높아진다.
함수를 만드는 과정 없이 한번에 처리할 수 있어 생산성이 높아지고, 병렬 프로그래밍이 용이하다.
4. 람다 방식
(매개변수) -> {실행문};
5. 람다 표현식 예제
5-1. 기본적인 활용
package ex07.ch02;
interface Can1 {
void run();
}
public class Beh01 {
static void start(Can1 can1) {
can1.run();
}
public static void main(String[] args) {
start(() -> {
System.out.println("달리자1");
});
start(() -> {
System.out.println("달리자2");
});
}
}

6. 람다 표현식 유형
package ex07.ch02;
/*
1. ConSumer
2. Supplier
3. Prediate (true or false) 논리 또는 예측
4. Function
5. Callable
*/
// 소비하는 친구
interface Con1 {
void accept(int n); // 받아서 소비하는 애
}
// 공급하는 친구
interface Sup01 {
int get(); // 호출해서 받는 애 -> 반드시 리턴값이 있어야 함
}
// 예견하는 친구
interface Pre01 {
boolean test(int n);
}
// 함수
interface Fun01 {
int apply(int n1, int n2);
}
// 기본
interface Cal01 {
void call();
}
// 절대 만들지마라!! 써먹기만 하면 된다.
public class Beh02 {
public static void main(String[] args) {
// 1. Consumer (소비자)
Con1 c1 = (int n) -> {
System.out.println("소비함 : " + n);
};
c1.accept(10);
// 2. Supplier (공급자)
Sup01 s1 = () -> 1; // {}를 안쓰면 자동으로 리턴코드가 된다.
int r1 = s1.get();
System.out.println("공급 받음 : " + r1);
// 3. Prediate (논리 또는 예측)
Pre01 p1 = (n) -> n % 2 == 0;
Pre01 p2 = (n) -> n % 3 == 0;
System.out.println("예측함 : " + p1.test(5)); // false
System.out.println("예측함 : " + p2.test(6)); // true
// 4. Function (함수)
Fun01 add = (n1, n2) -> n1 + n2;
Fun01 sub = (n1, n2) -> n1 - n2;
Fun01 mul = (n1, n2) -> n1 * n2;
Fun01 div = (n1, n2) -> n1 / n2;
System.out.println("함수 : " + add.apply(1, 2));
System.out.println("함수 : " + mul.apply(4, 5));
// 5. Callable
Cal01 ca1 = () -> {
};
ca1.call();
}
}
Consumer (소비자)
Supplier (공급자)
Prediate (논리 또는 예측)
Function (함수)
Callable (기본)
7. 람다 활용 예제
package ex07.ch02;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Beh03 {
public static void main(String[] args) {
// String s = "hello";
// System.out.println(s.startsWith("d"));
List<String> words = new ArrayList<>();
words.add("apple");
words.add("banana");
words.add("cherry");
words.removeIf(s -> s.contains("a"));
System.out.println(words);
}
}

Share article