람다식이란?

  • 익명함수 : 메서드의 이름과 반환값이 없이 간략하게 표현한 함
  • Java 8에서 도입된 기능으로, 익명함수를 간결하게 표현하는 방법이다.
  • 람다식을 통해 코드를 더 간결하고 가독성 높게 작성할 수 있다.
  • 기본 형태

    (parameters) -> expression
    // 또는
    (parameters) -> { statements; }
    

구성 요소

  1. 파라미터 리스트 : 람다식이 사용할 파라미터들이다 메서드의 파라미터와 유사하다. 괄호 안에 파라미터를 표현한다.
  2. 화살표 연산자 ->: 람다식의 파라미터와 본문을 구분한다.
  3. 본문 : 람다식이 실행할 코드이다. 표현식 또는 블록으로 구성될 수 있다.

예제

  1. 매개변수가 없고, 본문이 단일 표현식인 경우
    Runnable r = () -> System.out.println("Hello, world!");
    r.run();
    
  2. 매개변수가 있는 경우 ``` // 매개변수가 하나인 경우 Consumer consumer = (String s) -> System.out.println(s); consumer.accept("Hello, world!");

// 매개변수의 타입을 생략한 경우 Consumer consumer2 = s -> System.out.println(s); consumer2.accept("Hello, world!");


3. 매개변수가 여러개인 경우

BiFunction<Integer, Integer, Integer> sum = (a, b) -> a + b; int result = sum.apply(5, 3); System.out.println(result);


4. 본문이 여러 줄인 경우

BiFunction<Integer, Integer, Integer> max = (a, b) -> { if (a > b) { return a; } else { return b; } }; int maxValue = max.apply(5, 3); System.out.println(maxValue);


### 함수형 인터페이스
- 함수형 인터페이스 : 단 하나의 추상 메서드만 가지는 인터페이스, `@FunctionalInterface`르르 사용하여 함수형 인터페이스임을 명시할 수 있다.
- 람다식은 함수형 인터페이스의 인스턴스를 생성할 때 사용된다.
- java.util.funcion 패키지 : 일반적으로 자주 쓰이는 형식의 메서드를 함수형 인터페이스로 미리 정의해 놓은 패키지이다. 새로운 함수형 인터페이스를 정의하지 않고, 이 패키지의 인터페이스를 활용하여 재사용성을 높일 수 있다.

**주요 함수형 인터페이스**
|함수형 인터페이스|메서드|반환타입|설명|
|------|---|---|---|
|Consumer<T>|accept(T t)|void|입력을 받아서 처리하는 함수. 반환값이 없음|
|Supplier<T>|get()|T|입력 없이 출력을 생성하는 함수|
|Function<T, R>|apply(T t)|R|입력을 받아서 출력을 반환하는 함수|
|Predicate<T>|test(T t)|boolean|입력을 받아서 boolean 값을 반환하는 함수|
|BiFunction<T, U, R>|apply(T t, U u)|R|두 개의 입력을 받아서 출력을 반환하는 함수|

### 스프링 MVC에서 람다식 활용 예제
**Entity**

@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; }


**Repository**

public interface UserRepository extends JpaRepository<User, Long> { List findByName(String name); }


**Service**

@Service public class UserService {

@Autowired
private UserRepository userRepository;

public List<User> getUsersByName(String name) {
    return userRepository.findByName(name);
}

public List<String> getUserNamesByAge(int age) {
    List<User> users = (List<User>) userRepository.findAll();
    return users.stream()
                .filter(user -> user.getAge() > age)
                .map(User::getName)
                .collect(Collectors.toList());
} } ``` - users 리스트를 stream()으로 처리할 때 filter()를 통해 각 user 요소의 age 값이 매개변수 age값보다 큰 경우만을 거르는 조건을 람다식으로 처리하였다.