https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
https://www.w3schools.com/java/java_lambda.asp
https://java-8-tips.readthedocs.io/en/stable/lambdas.html
틀린 해석이 있다면 알려주세용 감사합니다 🍎
사실 현재도 코드 짤 때 쓰긴 쓰지만... 정확한 개념을 확실히 한번 해보고 싶어서 람다식에 대해서 한번 공부해보기로 했다
위에 문서를 보면 예제까지 들어가며 엄청 상세히 알려주고 있으니 참고.
그냥 for each 쓸 때 말고.. 더 활용할 수 있는 예제를 찾아보고 싶었다
다음번엔 JAVA 8 부터 도입된 Stream API 도 알아봐야겠다
람다 함수는 JAVA에서만 쓰는 건 아니고, 프로그래밍 언어에서 사용하는 개념이다
익명함수(Anonymous functions) 를 지칭하는 용어이고, 함수를 단순히 표현하는 방법이다
이 또한 JAVA 8에서 추가되었고, parameters 을 받아서 value로 리턴시켜 주는 구문을 짧게 표현할 수 있다
method와 유사하지만 이름이 필요없다
simplest lambda expression
parameter -> expression
more than one parameter, wrap them in parentheses
(parameter1, parameter2) -> expression
Expressions are limited. They have to immediately return a value, and they cannot contain variables, assignments or statements such as if or for. In order to do more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement.
(parameter1, parameter2) -> { code block }
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}
interface 를 사용하여 저장할 수도 있다
import java.util.ArrayList;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
Consumer<Integer> method = (n) -> { System.out.println(n); };
numbers.forEach( method );
}
}
interface StringFunction {
String run(String str);
}
public class Main {
public static void main(String[] args) {
StringFunction exclaim = (s) -> s + "!";
StringFunction ask = (s) -> s + "?";
printFormatted("Hello", exclaim);
printFormatted("Hello", ask);
}
public static void printFormatted(String str, StringFunction format) {
String result = format.run(str);
System.out.println(result);
}
}
For run() method fully described lambda expression is
() -> {
I love Lambdas".length();
}
and for call() it is
() -> {
return I love Lambdas".length();
}
- Variable declarations
- Assignment statements
- Return statements
- Method or constructor arguments
- Lambda expression bodies
- Ternary expressions, ?: etc
public static void main(String[] args) throws Exception {
execute(() -> "done"); // Line-1
}
static void execute(Runnable runnable) {
System.out.println("Executing Runnable...");
}
static void execute(Callable<String> callable) throws Exception {
System.out.println("Executing Callable...");
callable.call();
}
/* static void execute(PrivilegedAction<String> action) {
System.out.println("Executing PrivilegedAction...");
action.run();
} */
Output: Executing Callable...
Where to use Lambdas
We have discussed enough on lambdas and anonybmous classes. Let’s discuss the scenarios where should we use them.
Anonymous class:
- Use it whenever you want to declare some additional fields or methods which lambda can’t do.
Lambda:
- Use it if you want to encapsulate a single unit of behavior and pass to some other code. For example: performing certain operation on each element of collection.
- Use it if you need a simple instance of a functional interface and none of the preceding criteria apply (for example, you do not need a constructor, a named type, fields, or additional methods).
'Web > JAVA' 카테고리의 다른 글
[Java] Interface Supplier<T> (0) | 2023.03.22 |
---|---|
[Java] this (0) | 2023.03.22 |
[IntelliJ Javadocs] Javadocs 문서 만들기 (0) | 2023.03.18 |
[Java] try-with-resources (0) | 2023.02.25 |
[JAVA 8↑] Stream (0) | 2023.02.21 |