Spring/JAVA

[Java8 Lambda] Lambda Expressions

alsruds 2023. 10. 10. 05:17
🤹‍♂️Java Brains 강의🤹‍♂️

https://www.youtube.com/playlist?list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3

 

✨ Code in OOP

☑️ Object Oriented Programming (OOP) 에 문제가 있어서 Java8 Lambda 가 나온 것 (진짜?)

· Everything is an object

· All code blocks are 'associated' with classes and objects

 

✨ Why Lambdas?

· Enables functional programming

· Readable and concise code

· Easier to use APIs and libraries

· Enable support for parallel processing

 

✨ Introducing Lambda Expressions

☑️ Functions as values

// 코드가 한 줄일 때
aBlockOfCode = () -> ...

// 코드가 여러 줄일 때
aBlockOfCode = () -> { ... }

 

✨ Lambda Expression Examples

☑️ 람다 표현식으로 바꾸기

1. remove modifier (ex. public, private)
2. remove method name
3. remove data type (ex. int, double)

 

· 바꾸기 전 코드

doubleNumberFunction = public int double(int a) {
    return a * 2;
}

 

· 람다 표현식으로 바꾼 코드

// 코드가 한 줄이면 return 삭제 가능
doubleNumberFunction = (int a) -> a * 2;

 

· More Examples

addFunction = (int a, int b) -> a + b;

stringLengthCountFunction = (String s) -> s.length();

safeDivideFunction = (int x, int y) -> {
    if (y == 0) return 0;
    return a / b;
}