이번에는 Java 8을 공부해보려고 합니다.
첫 번째로 함수형 인터페이스를 공부해 보도록 하겠습니다.
1. 함수형 인터페이스란?
2. 함수형 인터페이스 구현해 보기
3. Java가 제공하는 함수형 인터페이스 사용해 보기
함수형 인터페이스란?
함수형 인터페이스는 Java에서 오직 하나의 추상 메서드만 가지는 인터페이스입니다.
이러한 인터페이스는 Java의 람다 표현식과 메서드 참조의 기초로 사용됩니다.
함수형 인터페이스는 어떤 수의 기본 메서드와 정적 메서드를 가질 수 있지만,
오직 하나의 추상 메서드만이 가질 수 있습니다.
추상 메서드는 하나의 메서드 시그니처만을 가져야 하며 값을 반환할 수도 있고 안할 수도 있습니다.
함수형 인터페이스는 개발자들에게 동작을 메소드 인자로 전달하는 것,
동적으로 동작을 구현하는 것, 람다 표현식 또는 메소드 참조의 사용을 통해 동작을 실행하는 것을 가능하게 합니다.
함수형 인터페이스는 또한 싱글 메소드 인터페이스 또는 SAM(Single Abstract Method) 인터페이스라고도 불려집니다.
- ChatGpt -
함수형 인터페이스를 요약해 보자면 이렇게 요약할 수 있겠다.
함수형 인터페이스는 오직 하나의 추상메서드만 가지는 인터페이스며, 람다표현식과 메서드 참조의 기초이다.
이제 함수형 인터페이스를 구현해 보자
함수형 인터페이스 구현해 보기
우리는 함수형 인터페이스를 구현해 볼 수 있는데 방법은 어렵지 않다.
@FunctionalInterface
public interface DoFunction {
int doFunction(int number);
}
사실 추상메서드 하나만 있는 인터페이스를 구현하면 되어서 어렵지는 않다.
@FunctionalInterface를 붙이면 해당 인터페이스가 함수형 인터페이스인지 아닌지 구별할 수 있다.
(만약 붙이고 2개 이상 쓰면 오류 난다.)
그리고 구현할 때 똑같이 구현하면 된다.
@Test
public void doFunctional(){
DoFunction doFunction = new DoFunction() {
@Override
public int doFunction(int number) {
return number;
}
};
System.out.println("doFunction return " + doFunction.doFunction(10));
}
해당 코드를 람다식으로도 바꿀 수 있는데
@Test
public void doFunctional(){
DoFunction doFunction = number -> number;
System.out.println("doFunction return " + doFunction.doFunction(10));
}
이렇게 간단하게 바꿀 수 있다.
Java가 제공하는 함수형 인터페이스 사용해 보기
Java가 제공하는 여러 함수형 인터페이스 Function, BiFunction, Consumer, Supplier, Predicate 등등 있지만
이번에는 Function만 알아보려고 한다.
자세한 내용은 https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
java.util.function (Java Platform SE 8 )
Interface Summary Interface Description BiConsumer Represents an operation that accepts two input arguments and returns no result. BiFunction Represents a function that accepts two arguments and produces a result. BinaryOperator Represents an operation u
docs.oracle.com
해당 링크에 엄청나게 많은 함수형 인터페이스가 있다.
Function 함수형 인터페이스는 하나의 인자를 받고 리턴해주는 함수형 인터페이스인데 해당 인터페이스는 이렇게 구현할 수 있다.
public class ReadFunction implements Function<String, String> {
@Override
public String apply(String book) {
return "Read a " + book;
}
}
클래스에 Function 함수형 인터페이스를 상속받아 apply method를 구현하고
@Test
public void functionTest(){
ReadFunction readFunction = new ReadFunction();
System.out.println(readFunction.apply("Narnia"));
}
}
ReadFunction 인스턴스 만들어주고 apply에 "Nania" 인자 넘겨주게 되면
read a Narnia
해당 결과를 볼 수 있다.
이거를 람다식으로 간편하게 표현할 수 있는데
public void functionTest(){
ReadFunction readFunction = new ReadFunction();
Function<String, String> lamdaFunction = (s) -> "Read a " + s;
System.out.println(readFunction.apply("Narnia"));
//람다식으로 표현
System.out.println(lamdaFunction.apply("나니아 연대기"));
}
클래스를 만들지 않고도 간편하게 사용할 수 있다.
Function 함수형 인터페이스에는 apply 말고도 2개의 메서드가 더 있는데 compose와 andThen이다.
compose - 함수형 인터페이스 실행 전 실행
andThen - 함수형 인터페이스 실행 후 실행
@Test
public void functionTest(){
ReadFunction readFunction = new ReadFunction();
Function<String, String> lamdaFunction = (s) -> "Read a " + s;
Function<String, String> endFunction = (e) -> e + " end";
Function<String, String> startFunction = (b) -> "People " + b;
System.out.println(readFunction.apply("Narnia"));
//람다식으로 표현
System.out.println(lamdaFunction.apply("나니아 연대기"));
//compose
Function<String, String> composeFunction = startFunction.compose(lamdaFunction);
System.out.println(composeFunction.apply("나니아 연대기"));
//andThen
Function<String, String> andThenFunction = lamdaFunction.andThen(endFunction);
System.out.println(andThenFunction.apply("나니아 연대기"));
}
}
Read a Narnia
Read a 나니아 연대기
People Read a 나니아 연대기
Read a 나니아 연대기 end
특이한 점은
compose를 보면 startFunction에다가 compose를 걸어두었는데 lamdaFunction이 아닌 startFunction에다가 걸어둔 이유는
lamdaFunction에 compose를 걸면 startFunction apply 된 거에 compose가 걸려서
Read a People 나니아연대기가 출력 되게 된다.
여기까지 함수형 인터페이스에 대해서 알아보았다.
다음은 람다 표현식에 대해서 알아보도록 하겠습니다. 감사합니다.
출처 : https://www.inflearn.com/course/the-java-java8/dashboard
더 자바, Java 8 - 인프런 | 강의
자바 8에 추가된 기능들은 자바가 제공하는 API는 물론이고 스프링 같은 제 3의 라이브러리 및 프레임워크에서도 널리 사용되고 있습니다. 이 시대의 자바 개발자라면 반드시 알아야 합니다. 이
www.inflearn.com
출차 : https://openai.com/blog/chatgpt/
ChatGPT: Optimizing Language Models for Dialogue
We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests. ChatGPT is
openai.com
'Java > 더 자바, Java 8' 카테고리의 다른 글
Optional (0) | 2023.03.07 |
---|---|
Stream 스트림 (0) | 2023.02.28 |
Interface Default Method, Static Method 인터페이스 디폴트 메소드, 정적 메소드 (0) | 2023.02.16 |
Method Reference, 메소드 레퍼런스 (0) | 2023.02.10 |
Lambda , 람다 표현식 (0) | 2023.02.08 |