Consumer

Consumer (소비자 함수형 인터페이스)

단일 입력 인자를 받고 결과를 반환하지 않는 연산을 나타내는 함수형 인터페이스예요. 대부분의 다른 함수형 인터페이스와 달리 부수 효과(side-effects)를 통해 동작할 것으로 기대돼요.

출처: Java API Reference

본문

Consumer<T>의 추상 메서드는 accept(T)로 하나의 인자를 받아 결과를 반환하지 않아요. 기본 메서드 andThen(Consumer)으로 두 Consumer를 순차 연결할 수 있어요.

@FunctionalInterface
public interface Consumer<T>
Consumer<String> print = s -> System.out.println(s);
Consumer<String> upper = s -> System.out.println(s.toUpperCase());
print.andThen(upper).accept("hello");
// hello
// HELLO

Iterable.forEachStream.forEach에 자주 사용돼요.

List<Integer> list = List.of(1, 2, 3);
list.forEach(n -> System.out.println(n * n));

함수형 메서드는 accept(Object)예요. 코드와 시그니처는 원문 그대로 보존돼요.

더 알아보기