자바 기초 스터디_22.01.26(수)
import java.util.function.Function; // import 해줘야 한다.
public class Plus10 implements Function<Integer, Integer> {
@Override
public Integer apply(Integer integer) {
return integer + 10;
}
}
public class Foo {
public static void main(String[] args) {
Plus10 plus10 = new Plus10();
System.out.println(plus10.apply(1)); // 11 출력
}
}
main 메소드 람다 표현식으로 바꾸기 🔻
public class Foo {
public static void main(String[] args) {
Function<Integer, Integer> plus10 = (i) -> i + 10;
System.out.println(plus10.apply(1)); // 11 출력
}
}
default로 제공하는 조합용 메소드(andThen, compose)를 활용하여 고차함수로 구현 가능 🔻
public class Foo {
public static void main(String[] args) {
Function<Integer, Integer> plus10 = (i) -> i + 10;
Function<Integer, Integer> multiply2 = (i) -> i * 2;
Function<Integer, Integer> multiply2AndPlus10 = plus10.compose(multiply2);
// 🔺 compose 메소드는 ()안의 함수(multiply2)를 먼저 실행하고,
// 리턴받은 값(2)을 plus10의 인자값으로 넣어주는 역할을 한다.
System.out.println(multiply2AndPlus10.apply(2); // (2(i) * 2) + 10 = 14 출력
}
}
import java.util.function.Consumer; // import 해줘야 한다.
public class Foo {
public static void main(String[] args) {
Consumer<Integer> printT = (i) -> System.out.println(i); // System.out 부분은 메소드 레퍼런스로 바꿀 수 있다.
printT.accept(10); // 10 출력
}
}
import java.util.function.Supplier; // import 해줘야 한다.
public class Foo {
public static void main(String[] args) {
Supplier<Integer> get10 = () -> 10; // () 인자값을 받지 않는다.
System.out.println(get10.get()); // 10 출력
}
}
and
or
negate
다양한 판단을 위해 함수 조합용 메소드를 제공한다.
import java.util.function.Predicate; // import 해줘야 한다.
public class Foo {
public static void main(String[] args) {
Predicate<String> startWithVans = (s) -> s.startsWith("V"); // 입력받은 인자가 V로 시작하는지 판단한다.
System.out.println(startWithVans.test("Vans")); // True 출력
}
}
//위 Function 예제
public class Foo {
public static void main(String[] args) {
Function<Integer, Integer> plus10 = (i) -> i + 10;
System.out.println(plus10.apply(1)); // 11 출력
}
}
Function<Integer, Integer> plus10에서 받는 타입과 리턴 타입이 같으므로
UnaryOperator로 바꿀수 있다.(+입력값이 하나일 경우) 🔻
public class Foo {
public static void main(String[] args) {
UnaryOperator<Integer> plus10 = (i) -> i + 10;
System.out.println(plus10.apply(1)); // 11 출력
}
}
이외에도 기본으로 제공하는 함수형 인터페이스가 다양한데, 일정한 규칙을 발견할 수 있다.
예를들면 함수명 앞에 Bi가 붙으면 입력값이 하나 증가하거나, Boolean이 붙으면 Boolean 타입의 값을
받는구나 라고 추측할 수 있다. 기본형 함수 인터페이스를 찾을때 이를 활용하여 찾으면 더 쉽게 찾고 쓸 수 있다.