푸린세스

Predicate의 결합, Function의 합성 Ex14_3 본문

카테고리 없음

Predicate의 결합, Function의 합성 Ex14_3

푸곰주 2022. 3. 28. 17:35
package ex14;

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

//자바정석3판
public class Ex14_3 {

	public static void main(String[] args) {
		//String 입력 Integer출력
		Function<String, Integer> f = (s) -> Integer.parseInt(s,16);
		//Integer입력 String 출력
		Function<Integer, String> g = (i) -> Integer.toBinaryString(i);
		
		
		
		//하나로 합칠 수 있다. 함수 f, 함수 g
		//2개를 마치 하나인것처럼 연결 -> andThen :f를적용하고 나서 g를 적용하라
		//f의 출력 = g의 입력 같아야 연결가능
		//새로운 함수 h로 만듬
		
		//h의 입력, h의 출력 
		Function<String,String> h = f.andThen(g); //함수 2개 연결
		Function<Integer, Integer> h2 = f.compose(g); //g.andThen(f)
		//함수결합방법 두가지. f->g or g->f      compose몰라도 됨 g.andthen(f)쓰면된다.
		
		
		System.out.println(h.apply("FF"));//FF->16진수로 해석 :255 -> 2진수문자열로 :1111111
		System.out.println(h2.apply(2));//2 -> 10 -> 16진수로해석 16
		
		Function<String, String> f2 = x -> x;//항등함수(identity function)
		System.out.println(f2.apply("AAA"));//하는일이없다.입력받은값을 그대로줌
		
		Predicate<Integer> p = i -> i <100; //입력을 Integer로 받음.결과를 boolean으로
		Predicate<Integer> q = i -> i <200;
		Predicate<Integer> r = i -> i%2 == 0;
		Predicate<Integer> notP = p.negate();//not, i>=100
		
		Predicate<Integer> all = notP.and(q.or(r)); //(i>=100 %% (i<200||i%2==0))
		System.out.println(all.test(150));         // 150>=100 T &&  (T || T)
													// T && T -> T
		String str1 = new String("abc");
		String str2 = new String("abc");
			//true라는 것은 등가비교연산자 안쓰고 equals메소드쓴다..
		Predicate<String> p2 = Predicate.isEqual(str1);
		//boolean result = str1.equals(str2);
		boolean result = Predicate.isEqual(str1).test(str2);
		System.out.println(result);     //true   "abc"=="abc"
							// new String("abc") == "abc" false
							//주소비교 false임,

	}

}