Java/객체지향

[객체지향][람다식/Lambda Expression] - Predicate의 결합. CF와 함수형 인터페이스

얄루몬 2022. 3. 9. 20:52

https://youtu.be/Kk1ZIrVZnqw?list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp 

📖본 포스팅은 '자바의 정석 - 남궁성 저자' 님의 책과 유튜브 강의를 보고 작성되었습니다.


[Predicate의 결합]

  • Predicate는 조건식으로 and(), or(), negate()로 두 Predicate를 하나로 결합 가능하다.(default 메서드)
  • 함수형 인터페이스가 가질 수 있는 메서드
    • default 메서드
    • static 메서드
    • 추상 메서드(abstract)
  • 등가 비교를 위한 Predicate의 작성에는 isEqual()을 사용한다.(static메서드)

[실습]

[andThen]

  • 이때 함수의 출력과 입력이 타입이 같아야 andThen 사용이 가능하다.
  • 이때 새로 만들어지는 h는 입력 String 출력 String타입이 된다. h<String, String> 이런식!
  • andThen은 f를 앞에 세우고 g를 뒤에 세운다.

[compose]

  • 이때도 함수의 출려과 입력의 타입이 같아야 compose 사용이 된다. 
  • 이때 새로 만들어지는 h2는 입력이 Integer 출력 Integer타입이 된다. h2<Integer, Integer> 이런식!
  • compose나 andThen 원하는 걸 써주면 된다.
package javajungsuk;

import java.util.function.Function;
import java.util.function.Predicate;

public class Java14_3 {

	public static void main(String[] args) {
		//함수도 람다식으로 연결할 수 있다는 것을 보여줌
		Function<String, Integer> f = (s) -> Integer.parseInt(s,16);
		Function<Integer, String> g = (i) -> Integer.toBinaryString(i);
		
		Function<String, String> h = f.andThen(g);
		Function<Integer, Integer> h2 = f.compose(g);
		
		System.out.println(h.apply("FF"));
		System.out.println(h2.apply(2));
		
		//항등 함수 넣은 값(입력 값) 그대로 출력
		Function<String, String> f2 = x -> x;
		System.out.println(f2.apply("AAA"));
		
		//
		Predicate<Integer> p = i -> i < 100;
		Predicate<Integer> q = i -> i < 200;
		Predicate<Integer> r = i -> i % 2==0;
		Predicate<Integer> notP = p.negate();
		
		Predicate<Integer> all = notP.and(q.or(r));
		System.out.println(all.test(150));
		
		String str1 = "abc";
		String str2 = "abc";
		
		//str1과 str2가 같은지 비교한 결과 반환
		Predicate<String> p2 = Predicate.isEqual(str1);
		boolean result = p2.test(str2);
		System.out.println(result);
	}

}

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

  • 함수형 인터페이스를 사용하는 컬렉션 프레임워크의 메서드

[실습]

import java.util.*;

class LambdaEx4 {
	public static void main(String[] args) 	{
		ArrayList<Integer> list = new ArrayList<>();
		for(int i=0;i<10;i++)
			list.add(i);

		// list의 모든 요소를 출력
		list.forEach(i->System.out.print(i+","));
		System.out.println();

		// list에서 2 또는 3의 배수를 제거한다.
		list.removeIf(x-> x%2==0 || x%3==0);
		System.out.println(list);

		list.replaceAll(i->i*10); // list의 각 요소에 10을 곱한다.
		System.out.println(list);

		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");
		map.put("4", "4");

		// map의 모든 요소를 {k,v}의 형식으로 출력한다.
		map.forEach((k,v)-> System.out.print("{"+k+","+v+"},"));
		System.out.println();
	}
}