[Java] 14. 람다표현식

김주희's avatar
Feb 26, 2025
[Java] 14. 람다표현식
💡
functional interface
함수
소비
공급
논리
호출

1. 람다 기본

  1. 인터페이스의 메소드(행위) 전달 방법 중 하나로 익명 클래스를 내부적으로 만들어 메소드를 간결하게 전달할 수 있다.
  1. 람다식을 사용하면 인터페이스를 구현한 객체를 만드는 것과 동일하다.
() -> {} (): 전달하고자 하는 함수의 인수 자리 {}: 전달하고자 하는 함수의 구현체
 

2. 람다 유형

💡
1. Consumer 2. Supplier 3. Predicate (true or false) 논리 4. Function 5. Callable
package ex07.ch02; /* 람다 유형 1. Consumer 2. Supplier 3. Predicate (true or false) 논리 4. Function 5. Callable */ // 소비하는 친구 (가져다 쓰기만 한다 => return X / 인수로 받는) 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) -> { // c1은 함수를 가지고 있는 것 System.out.println("소비함: " + n); }; c1.accept(10); // 2. Supplier // s1이 1이라는 값을 들고 있는 것이 아니라 함수를 가지고 있는 것 Sup01 s1 = () -> 1; // {} 안쓰면 자동 return 코드가 됨 int r1 = s1.get(); System.out.println("공급받음: " + r1); // 3. Predicate Pre01 p1 = (n) -> n % 2 == 0; // return이 한 줄일 때만 Pre01 p2 = (n) -> n % 3 == 0; System.out.println("예측함: " + p1.test(5)); System.out.println("예측함: " + p2.test(6)); // 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 cal1 = () -> { System.out.println("기본 함수"); }; cal1.call(); } }
notion image

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<String>(); words.add("apple"); words.add("banana"); words.add("cherry"); words.removeIf(s -> s.contains("a")); System.out.println(words); } }
notion image
Share article

jay0628