본문 바로가기

하../java

ch14 java.util.function 패키지

자주 사용되는 다양한 함수형 인터페이스를 제공

표준화 된다는 장점

java.lang.Runnable : 입력값도 없고 출력값도 없을때 사용

Supplier<T> : 입력값은 없고 출력값만 있을때 사용 (공급자)

Consumer<T> : 입력값만 있고 출력값이 없음 (소비자)

Function<T,R> : 입력값도 있고 출력값도 있음(함수)

Predicate<T> : 입력값을 True, False로 반환(조건식)

 

Predicate<String> isEmptyStr = s -> s.length()==0;
String s = "";

if(isEmptyStr.test(s) // test는 메소드 이름 if(s.length()==0) 코드와 같음
 System.out.println("This is an empty String.");
Supplier<Integer> f = (int)(Math.random()*100)+1; - 공급자
Consumer<Integer> = i -> System.out.print(i+", "); - 소비자
Predicate<Integer> f = i -> i%2==0; (조건식)
- Integer을 쓰는 이유는 반환타입이 항상 Boolean이기 때문에 Boolean은 사용하지 않음
Function<Integer> f = i -> i/10*10;

 

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

 

Bi 2개를 의미함

BiConsumer<T,U> 두개만 받기 

BiPredicate<T,U> - boolean

BiFunction<T,U,R> 두개를 받아서의 결과 출력

 

3개 매개변수는 없기때문에 직접 만들어야함.

 

매개변수의 타입과 반환 타입이 일치하는 함수형 인터페이스

 

단항 연산자, 다항 연산자 매개 변수 타입과 결과 타입이 같음(int + int -> int)

	public static void main(String[] args) {
		Supplier<Integer>  s = ()-> (int)(Math.random()*100)+1; //1~100난수
		Consumer<Integer>  c = i -> System.out.print(i+", "); 
		Predicate<Integer> p = i -> i%2==0; //짝수인지 검사 
		Function<Integer, Integer> f = i -> i/10*10; // i의 일의 자리를 없앤다.
		
		List<Integer> list = new ArrayList<>();	
		makeRandomList(s, list); //list를 랜덤값으로 채운다
		System.out.println(list);
		printEvenNum(p, c, list); //짝수를 출력.
		List<Integer> newList = doSomething(f, list);
		System.out.println(newList);
	}

	static <T> List<T> doSomething(Function<T, T> f, List<T> list) {
		List<T> newList = new ArrayList<T>(list.size());

		for(T i : list) {
			newList.add(f.apply(i)); //일의 자리를 없애서 새로운 list에 저장.
		}	

		return newList;
	}

//	Consumer<Integer>  c = i -> System.out.print(i+", "); 
//	Predicate<Integer> p = i -> i%2==0; //짝수인지 검사 
	static <T> void printEvenNum(Predicate<T> p, Consumer<T> c, List<T> list) {
		System.out.print("[");
		for(T i : list) {
			if(p.test(i)) //짝수인지 검사
				c.accept(i); //화면에 i 출력.
		}	
		System.out.println("]");
	}

	static <T> void makeRandomList(Supplier<T> s, List<T> list) {
		for(int i=0;i<10;i++) {
			list.add(s.get()); // Supplier로 부터 1~100의 난수를 받아서 list에 추가
		}
	}
결과
[56, 57, 38, 80, 47, 87, 26, 33, 98, 10] 랜덤 10개의 수
[56, 38, 80, 26, 98, 10, ] 짝수만 출력
[50, 50, 30, 80, 40, 80, 20, 30, 90, 10] 일의 자리를 없앰

 

 

 

 

'하.. > java' 카테고리의 다른 글

ch14 스트림 스트림의 특징  (0) 2021.12.26
ch14 Predicate의 결합 CF와 함수형 인터페이스  (0) 2021.12.26
ch14 함수형 인터페이스  (0) 2021.12.25
ch14 람다식 작성하기  (0) 2021.12.25
ch13 wait()과 notify()  (0) 2021.12.25