cTosMaster 2025. 3. 14. 17:42

1. 람다식이란? 

    람다식은 자바에서 익명 함수를 쉽게 표현하는 방법이야.
    즉, 메서드를 간단하게 표현할 수 있는 식으로, 코드를 더 간결하고 가독성 있게 만들어줘!

    람다식을 사용하려면 "함수형 인터페이스" 가 필요하다.

 

    ☝️함수형 인터페이스(Functional Interface)란? 

        ✔ 추상 메서드가 단 하나만 있는 인터페이스 (인자 여러개 가능)
        ✔ @FunctionalInterface 어노테이션을 붙이면 컴파일러가 확인해줌.

@FunctionalInterface
interface MyFunctionalInterface {
    void myMethod();  // 추상 메서드가 1개만 있어야 함!
}

 

* 람다식 구문

(int x, int y) -> { return x + y; } // 기존 방식

(x, y) -> x + y // 타입 생략 가능

 

case1 : 매개변수가 없는 경우

() -> System.out.println("Hello World!");

 

case2: 매개변수가 하나인 경우

x -> x * x;

 

case 3: 매개변수가 여러 개인 경우

(x, y) -> x + y;

 

case4 실행문이 여러 개일 경우

(x, y) -> {

int sum = x + y;

return sum;

 

2. 람다식 사용 예제

//익명 클래스 예시 (변환 전) 
public class LambdaExample {
    public static void main(String[] args) {
        MyFunctionalInterface example = new MyFunctionalInterface() {
            @Override
            public void myMethod() {
                System.out.println("Hello, World!");
            }
        };
        example.myMethod();
    }
}
익명 클래스를 사용하면 코드가 길어지고 가독성이 떨어져!

//람다식 사용 예시 (변환 후)
public class LambdaExample {
    public static void main(String[] args) {
        MyFunctionalInterface example = () -> System.out.println("Hello, World!");
        example.myMethod();
    }
}

✅ 익명 클래스를 람다식으로 바꾸니 코드가 훨씬 간결해짐.

 

3. 자바에서 제공하는 대표적인 함수형 인터페이스

(*) java.util.function 패키지 제공

1) Consumer<T> 매개변수만 있고 반환값 없음 void accept(T t)
2) Supplier<T> 매개변수 없고 반환값 있음 T get()
3) Function<T, R> 매개변수 1개, 반환값 있음 R apply(T t)
4) Predicate<T> 매개변수 1개, boolean 반환 boolean test(T t)

 

    1) Consumer<T> 예제 (입력만 있고 출력 없음)

import java.util.function.Consumer;

public class LambdaExample {
    public static void main(String[] args) {
        Consumer<String> printer = message -> System.out.println("Message: " + message);
        printer.accept("Hello, Lambda!");  // 출력: Message: Hello, Lambda!
    }
}

 

 

    2) Supplier<T> 예제 (입력만 있고 출력 없음)

import java.util.function.Supplier;

public class LambdaExample {
    public static void main(String[] args) {
        Supplier<Double> randomSupplier = () -> Math.random();
        System.out.println(randomSupplier.get());  // 랜덤 숫자 출력
    }
}

 

   3) Function<T, R> 예제 (입력 -> 출력 변환)

import java.util.function.Function;

public class LambdaExample {
    public static void main(String[] args) {
        Function<String, Integer> lengthFunction = str -> str.length();
        System.out.println(lengthFunction.apply("Lambda"));  // 6
    }
}

 

  4) Predicate<T>, IntPredicate<T> 예제 (입력 -> boolean 반환)

import java.util.function.Predicate;

public class LambdaExample {
    public static void main(String[] args) {
        Predicate<Integer> isEven = num -> num % 2 == 0;
        System.out.println(isEven.test(10)); // true
        System.out.println(isEven.test(7));  // false
    }
}

//IntPredicate
import java.util.function.IntPredicate;
import java.util.function.Predicate;

// Predicate: 입력값을 받아서 조건을 체크한 후 true 또는 false를 반환하는 인터페이스 boolean test(T t),
// -> 조건 집합을 정의하고 지정된 객체가 조건을 충족하는지 유무를 확인하는 메서드

public class PredicateTest {

	public static void main(String[] args) {
			Predicate<String> i  = (s)-> s.length() >10; //(1)
		    System.out.println(i.test("getting strart java"));	//(2)	   
		    
		    IntPredicate p1 = n -> (n % 3) == 0; //(3) 3의 배수 판정
		    IntPredicate p2 = n -> (n % 5) == 0;//(4) 5의 배수 판정		    
		    IntPredicate p_res = p1. and (p2); //(5)  두 조건 and 연산
		    
		    System.out.println(p_res.test(3)); //(6)
		    System.out.println(p_res.test(4)); //(7)
		    
		    IntPredicate p_res02 = p1. or (p2); //(8)
		    System.out.println(p_res02.test(5)); 
		    System.out.println(p_res02.test(15));
		    
		    
		    Predicate<String> str  = Predicate.isEqual("Dominica_kim");//(9)
		    System.out.println(str.test("Dominica_kim"));
	}

}