프로그래밍 언어/Java

[Java] 함수형 인터페이스(Functional Interface) 활용

happy_life 2022. 7. 5. 15:54

함수형 인터페이스(Functional Interface)

 

함수형 인터페이스 개요

함수형 인터페이스는 추상메서드가 1개인 인터페이스를 의미한다. 하지만 대부분의 경우 개발자가 함수형 인터페이스를 직접 구현하는 경우는 없다. Function 패키지에서  다양한 함수형 인터페이스를 이미 제공하고 있기 때문이다.

 

기본 함수형 인터페이스

함수형 인터페이스 메서드 설명
Runnable void run() 매개변수X, 반환값X
Supplier<T> T get() 매개변수X, 반환값O
Consumer<T> void accept(T t) 매개변수O, 반환값X
Function<T,R> R apply(T t)) 매개변수O, 반환값O
Predicate<T> boolean test(T t) 조건식 표현에 사용 매개변수 하나, 반환 타입 boolean

 

Runnable

// 매개변수 X, 반환값 X
Runnable runnable = () -> System.out.println("하하하");
runnable.run();

 

Supplier

// 매개변수 X, 반환값 O
Supplier<Integer> supplier = () -> ((int) (Math.random() * 100));
System.out.println("supplier.get(): " + supplier.get());

 

Consumer

// 매개변수 O, 반환값 X
Consumer<String> consumer = s -> System.out.println(s.toUpperCase());
consumer.accept("hello");

 

Function

// 매개변수 1개, 반환값 O
Function<String, String> function = s -> (s + "입니다.");
System.out.println("function 반환값: " + function.apply("ㅇㅇㅇ"));

 

Predicate

// 매개변수 1개, 반환 타입 boolean
Predicate<Integer> predicate = a -> a < 100;
System.out.println("predicate = " + predicate.test(10));
728x90

 

매개변수가 두 개인 함수형 인터페이스

함수형 인터페이스 메서드 설명
BiConsumer<T,U> void accept(T t, U u) 두개의 매개변수만 있고, 반환값 X
BiPredicate<T,U> boolean test(T t, U u) 조건식을 표현하는데 사용됨, 매개변수는 둘 반환값은 boolean
BiFunction<T,U,R> R apply(T t, U u) 두 개의 매개변수를 받아 하나의 결과 반환

 

 

BiConsumer

// 매개 변수 2개인 Consumer
BiConsumer<String, String> biConsumer = (a, b) -> System.out.println(a+b);
biConsumer.accept("hello", " world");

 

BiPredicate

// 매개 변수 2개인 Predicate
BiPredicate<Integer, Integer> biPredicate = (a, b) -> a + b < 10;
System.out.println("biPredicate.test(1,4) = " + biPredicate.test(1,4));

 

BiFunction

// 매개 변수 2개인 Function
BiFunction<String, String, String> biFunction = (a,b) -> a+b;
System.out.println("biFunction.apply(\"Hello\", \"World\") = " + biFunction.apply("Hello", " World"));

 

 

컬렉션 프레임 워크와 함수형 인터페이스

컬렉션 프레임 워크에 다수의 디폴트 메서드가 추가되었는데, 그 중 일부는 함수형 인터페이스를 사용한다.

 

replaceIf

//removeIf - Predicate
arrayList.removeIf(i -> i % 3 == 0);
System.out.println();
System.out.println("removeIf -> arrayList = " + arrayList);

조건에 맞는 요소를 삭제한다.

 

forEach

//forEach - Consumer
arrayList.forEach(i -> System.out.print(i+", "));

모든 요소에 순차적으로 Consumer에 담긴 액션을 수행한다.

 

 

//HashMap
HashMap<String, String> map = new HashMap<>();
map.put("1", "김수박");
map.put("2", "이수박");
map.put("3", "최수박");

//forEach - BiConsumer
map.forEach((k,v) -> System.out.print("{" + k + "," + v + "}" + " , "));

모든 요소에 순차적으로 Consumer에 담긴 액션을 수행한다.

 

replaceAlll

//replaceAll - UnaryOperator - Function과 비슷한 것으로 Function과 달리 입출력 타입이 같다.
arrayList.replaceAll(i -> i * 10);
System.out.println("replaceAll -> arrayList = " + arrayList);

모든 요소에 치환 작업을 수행한다.