2025๋ 3์ 20์ผ
ํจ์ํ ํ๋ก๊ทธ๋๋ฐ(Functional Programming)์ ์์ ํจ์(Pure Function)๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ณ๊ฒฝํ์ง ์๊ณ ์ฐ์ฐ์ ์ํํ๋ ํ๋ก๊ทธ๋๋ฐ ํจ๋ฌ๋ค์์ด๋ค.
๊ธฐ์กด ๋ช
๋ นํ ํ๋ก๊ทธ๋๋ฐ(Imperative Programming)๊ณผ ๋ค๋ฅด๊ฒ, ๋ฐ์ดํฐ์ ๋ณ๊ฒฝ ์์ด ์ ์ธ์ ์ผ๋ก ์ฐ์ฐ์ ์ํํ๋ ๋ฐฉ์์ ๋ฐ๋ฅธ๋ค.
์์ ํจ์(Pure Function)
๋ถ๋ณ์ฑ(Immutability)
๊ณ ์ฐจ ํจ์(Higher-Order Function)
์ผ๊ธ ๊ฐ์ฒด(First-Class Citizen)
์ ์ธํ ํ๋ก๊ทธ๋๋ฐ(Declarative Programming)
// ์์ ํจ์ ์์ : ์
๋ ฅ๊ฐ์ด ๊ฐ์ผ๋ฉด ํญ์ ๋์ผํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํจ
public class PureFunctionExample {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3)); // 5
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ImmutabilityExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// ์๋ณธ ๋ฆฌ์คํธ ๋ณ๊ฒฝ ์์ด ์๋ก์ด ๋ฆฌ์คํธ ์์ฑ
List<Integer> doubledNumbers = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
System.out.println("์๋ณธ ๋ฆฌ์คํธ: " + numbers);
System.out.println("๋ณ๊ฒฝ๋ ๋ฆฌ์คํธ: " + doubledNumbers);
}
}
๐น ์ถ๋ ฅ ๊ฒฐ๊ณผ
์๋ณธ ๋ฆฌ์คํธ: [1, 2, 3, 4, 5]
๋ณ๊ฒฝ๋ ๋ฆฌ์คํธ: [2, 4, 6, 8, 10]
import java.util.function.Function;
public class HigherOrderFunctionExample {
public static void main(String[] args) {
Function<Integer, Integer> square = (n) -> n * n;
System.out.println(square.apply(5)); // 25
}
}
import java.util.function.Function;
public class FirstClassFunctionExample {
public static void main(String[] args) {
Function<Integer, Integer> doubleValue = (n) -> n * 2;
System.out.println(applyFunction(doubleValue, 10)); // 20
}
public static int applyFunction(Function<Integer, Integer> func, int value) {
return func.apply(value);
}
}
for
๋ฌธ์ ์ฌ์ฉํ์ง ์๊ณ , stream
์ ์ฌ์ฉํ์ฌ ๊ฐ๊ฒฐํ๊ฒ ํํ.import java.util.Arrays;
import java.util.List;
public class DeclarativeExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// ๋ช
๋ นํ ์คํ์ผ
for (int i = 0; i < numbers.size(); i++) {
System.out.print(numbers.get(i) + " ");
}
System.out.println();
// ์ ์ธํ ์คํ์ผ
numbers.forEach(n -> System.out.print(n + " "));
}
}
๐น ์ถ๋ ฅ ๊ฒฐ๊ณผ
1 2 3 4 5
1 2 3 4 5
์๋ฐ๋ ๋๋ค ํํ์(Lambda Expression) ๋ฐ ์คํธ๋ฆผ API(Stream API) ๋ฅผ ํ์ฉํ์ฌ ํจ์ํ ํ๋ก๊ทธ๋๋ฐ์ ์ง์ํ๋ค.
๋๋ค ํํ์์ ์ต๋ช ํจ์๋ฅผ ๊ฐ๋จํ๊ฒ ํํํ ์ ์๋๋ก ์ง์ํ๋ ๊ธฐ๋ฅ์ผ๋ก, ๋ณด์ผ๋ฌํ๋ ์ดํธ ์ฝ๋๋ฅผ ์ค์ผ ์ ์๋ค.
// ๋ ์ซ์๋ฅผ ๋ํ๋ ๋๋ค ํํ์
(int a, int b) -> a + b
๐ ํจ์ํ ํ๋ก๊ทธ๋๋ฐ ๊ฐ๋ ์ ๋ฆฌ
๐ ๋๋ค & ์คํธ๋ฆผ API ๊ด๋ จ ์๋ฃ