자바의 정석 - 람다와 스트림 (2)

송용준·2023년 6월 3일

java.util.function 패키지 (1/3)

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

  • Quiz

  1. Supplier< Integer >
  2. Consumer< Integer >
  3. Predict< Integer >
  4. Function< Integer >

java.util.function 패키지 (2/3)

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

    없으면 만들어 써라

java.util.function 패키지 (3/3)

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

Predicate의 결합

  • and(), or(), negate()로 두 Predicate를 하나로 결함(default 메서드)
  • 계산식을 합칠 수 있음
  • boolean 타입으로 반환
  • 등가 비교를 위한 Predicate의 작성에는 isEqual()를 사용(static메서드)
import java.util.function.Function;
import java.util.function.Predicate;

class Java {
	public static void main(String[] args)  {												// String : 입력 , Integer : 출력
		Function<String, Integer>		f = (s) -> Integer.parseInt(s,16);		// 16진수
		Function<Integer, String> 	g = (i) -> Integer.toBinaryString(i);		// 2진수 문자열
		
		Function<String, String> 		h = 		f.andThen(g);						// 입력, 출력 ( String -> Integer -> String) 
		Function<Integer, Integer>	h2 = 	f.compose(g);
		
		System.out.println(h.apply("FF"));			// "FF" -> 255 -> "111111"
		System.out.println(h2.apply(2));			// 2 -> "10" -> 16
		
		Function<String, String> 	f2 = x -> x;	// 항등 함수(identity function). 들어온대로 나간다.
		System.out.println(f2.apply("AAA"));		// 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();		// i >= 100. negate : 조건식 반대
		
		Predicate<Integer> all = notP.and(q.or(r));
		System.out.println(all.test(150));					// true
		
		String str1 = new String("abcd") ;
		String str2 = new String("abc") ;
		
		Predicate<String> p2 = Predicate.isEqual(str1);
		//boolean result = p2.test(str2);
		boolean result = Predicate.isEqual(str1).test(str2);
		System.out.println(result);
	}
}

컬렉션 프레임웍과 함수형 인터페이스

  • 함수형 인터페이스를 사용하는 컬렉션 프레임웍의 메서드(와일드 카드 생략)
import java.util.*;

class Java {
	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);
		
		// list에서 2또는 3의 배수를 제거한다.
		list.removeIf(x -> x%2 == 0 || x % 3 == 0);
		System.out.println(list);
		
		list.replaceAll(i -> i*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();
	}
}

E = MC²
Error = More Code² // 코드가 많아지면 에러가 두배로 많아진다.

profile
용용

0개의 댓글