java.util.function package 의 표준 API
자주 사용되는 함수적 표준 interface를 java.util.function package에 정의 ㅏ
주로 메서드 또는 생성자의 parameter로 Lambda 식을 제공하기 위함
Runnable void run ()
Consumer void accept (T)
Supplier T get ()
Function T apply (R) 새로운 타입으로 변환해서 리턴
Operation T XXX(T) 동일한 타입으로 연산 결과 리턴
Predicate boolean test (T) parameter를 조사해서 return 결정 🚨
Consumer 계열 -> .accept()
P는 Int, Long, Double p는 int, long, double 을 나타낸다.
Consumer<String> consumer = x -> System.out.println(x);
consumer.accept("Hello");
ObjIntConsumer<String> consumer2 = (name,repeat) -> {
for(int i = 0 ; i < repeat; i++){
System.out.println(name);
}
};
consumer2.accept("홍길동",2);
Supplier 계열 -> .get()
parameter는 없으며 return이 있는 형태
Supplier<String> supplier = () -> "Hello";
System.out.println(supplier.get());
IntSupplier supplier2 = () -> {
Random random = new Random();
return random.nextInt(6);
};
System.out.println(supplier2.getAsInt());
Function 계열 -> .apply()
parameter 와 return 값이 있는 형태
주로 파라미터를 이용해 연산을 수행한 후 원하는 타입으로 반환하는 역할
Function<String,Integer> function = (src) -> src.length();
System.out.println(function.apply("hello"));
ToIntBiFunction<String,String> function2 =
(src1,src2) -> Integer.parseInt(src1) + Integer.parseInt(src2);
System.out.println(function2.applyAsInt("4","5"));
Operator 계열 -> .apply() , 만약 타입 맞추려면 applyAsDouble(100,200));
동일타입리턴
UnaryOperator<Double> operator = (x) -> Math.pow(x,2);
System.out.println(operator.apply(10.0));
DoubleBinaryOperator operator2 = (x,y) -> Math.max(x,y);
System.out.println(operator2.applyAsDouble(100,200));
Predicate 계열 ! (굉장히 많이 씀) .test();
parameter를 받고 boolean 타입을 리턴
Predicate<String> predicate = (name) -> name.contains("Java");
System.out.println(predicate.test("JavaScript"));
DoublePredicate predicate2 = (num) -> num > 5;
System.out.println(predicate.t
API에서 사용된 표준 functional interface의 예
default void forEach(BiConsumer<? super K, ? super V> action){}
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {}
default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {}
메서드 참조
람다 실행문 내부에서 다른 함수 하나만을 실행하는 경우
컬렉션, 배열 등 데이터 소스에 대한 공통된 접근 방식 제공
손쉬운 병렬처리
맵/리듀스 모델 지원
중간 처리들과 최종 처리를 조합해서 사용
각각의 중간 처리는 새로운 스트림을 리턴하여 builder 패턴 적용
최종 처리는 최종적으로 원하는 값(void 포함)을 반환
Stream에 대한 개념을 잡았고 어렵지 않지만 익숙해져야 한다
그러기 위해서는 많은 실습을 해봐야 할 듯 지금은 힘들지만 시간내서 실습하는 시간을 가집시다!