본문 바로가기

Java

자바 - 람다식

목차

  1. 람다식은 언제 사용 가능할까?
  2. 사용 예제

생각보다 어렵다. 다시 공부하는 이유는 stream, spring API를 잘 사용하기 위해서 사용 예제 위주로 정리해보려고 한다.

 

1. 람다식은 언제 사용 가능할까?

 

함수형 인터페이스 일 때 사용 가능하다.

함수형 인터페이스란 구현해야하는 메서드가 오직 한개인 인터페이스

 

1.1 람다식 장단점

장점

- 간결함

- 병렬 프로그래밍 용이(이유는 모르겠다.)

 

단점

- 디버깅이 어렵다

- 초보자의 입장에선 가독성이 떨어진다.

 

2. 사용 예제 

 

2.1 리턴 값이 없을 때

사용할 함수형 인터페이스

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

 

2.1.1 인터페이스를 객체로 구현해서 사용

 

Consumer<Integer> consumer = new Consumer<>() {
    @Override
    public void accept(Integer integer) {
        System.out.println(integer);
    }
};

list.stream().forEach(consumer);

 

2.1.2 인터페이스를 익명 함수로 구현해서 사용

 

list.stream().forEach(new Consumer<Integer>() {
    @Override
    public void accept(Integer integer) {
        System.out.println(integer);
    }
});

 

 

2.1.3 인터페이스를 람다식으로 구현해서 사용

 

list.stream().forEach(integer -> {
    System.out.println();
});

 

2.2 리턴 값이 존재 할 때

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

 

2.2.1 인터페이스를 객체로 구현해서 사용

 

Predicate<Integer> predicate = new Predicate<>() {
    @Override
    public boolean test(Integer integer) {
        return integer > 3;
    }
};

Stream<Integer> stream = list.stream().filter(predicate);

 

2.2.2 인터페이스를 익명 함수로 구현해서 사용

 

Stream<Integer> stream = list.stream().filter(new Predicate<Integer>() {
    @Override
    public boolean test(Integer integer) {
        return integer > 3;
    }
});

 

2.2.3 인터페이스를 람다식으로 구현해서 사용

 

list.stream().filter(integer -> {return integer > 3;});

 

아래 처럼 return 을 생략할 수 도 있다. 대신 중괄호, 세미콜론도 지워야 가능하다.

list.stream().filter(integer -> integer > 3);