[JAVA] 14. 람다표현식

최재원's avatar
Feb 17, 2025
[JAVA] 14. 람다표현식
Functional Interface
소비
공급
논리
함수
호출
() → {}

1. 람다 기본

package ex07.ch02; // 1. 인터페이스로 정의 interface Can1 { // 2. 1개만 만든다. 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"); }); } }

2. 람다 유형

package ex07.ch02; /** * 1. Consumer * 2. Supplier * 3. Predicate (true or false) 논리 * 4. Function * 5. Callable */ // 소비자 interface Con01 { 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 Con01 c1 = (n) -> { System.out.println("소비: " + n); }; c1.accept(1); // 2. Supplier Sup01 s1 = () -> 1; // 1줄만 사용하면 자동 return int r1 = s1.get(); System.out.println("공급: " + r1); // 3. Predicate Pre01 p1 = (n) -> n > 0 ? true : false; boolean r2 = p1.test(1); System.out.println("예측: " + r2); // 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("함수: " + sub.apply(1, 2)); // 5. Callable Cal01 cal1 = () -> { System.out.println("호출: 기본함수"); }; cal1.call(); } }

3. 람다 활용

package ex07.ch02; import java.util.ArrayList; import java.util.List; public class Beh03 { public static void main(String[] args) { // String s = "hello"; // System.out.println(s.startsWith("h")); 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

jjack1