π λμ νλΌλ―Έν°λ?
- μμ§μ μ΄λ»κ² μ€νν κ²μΈμ§ κ²°μ νμ§ μμ μ½λ λΈλ‘μΌλ‘ λμ€μ μ€νλ λ©μλμ μΈμλ‘ μ½λ λΈλ‘μ μ λ¬νλ κ²
μ¦, μνλ λμμ λ©μλμ μΈμλ‘ μ λ¬ ν μ μμ
π λμ νλΌλ―Έν°ν μ¬μ© μ΄μ
- λ°λλ μꡬ μ¬νμ ν¨κ³Όμ μΌλ‘ λμν μ μμ
π μμ
λμ₯ μ¬κ³ λͺ©λ‘ μ ν리μΌμ΄μ 리μ€νΈμ μꡬμ¬ν
- λ Ήμ μ¬κ³Όλ§ νν°λ§
- λΉ¨κ° μ¬κ³Όλ§ νν°λ§
- λ¬΄κ±°μ΄ μ¬κ³Όλ§ νν°λ§
- κ°λ²Όμ΄ μ¬κ³Όλ§ νν°λ§
- ...
μ²μμλ 1λ²μ μꡬμ¬νλ§ μ‘΄μ¬ νλ€κ°, λμ€μ 2λ²μ μꡬμ¬νμ΄ μΆκ°λ μ μμ΅λλ€.
μ΄λ΄ κ²½μ° μλμ κ°μ΄ μμ νλΌλ―Έν°ν μμΌμ νν°λ§ λ©μλλ₯Ό ꡬνν μ μμ΅λλ€.
pulbic static List<Apple> filterAppleByColor(List<Apple> aplleList, Color color) {
List<Apple> result = new ArrayList<>();
for (Apple apple: inventory) {
if ( apple.getColor().equals(color) ) {
result.add(apple);
}
}
return result;
}
νμ§λ§ 3λ², 4λ²κ³Ό κ°μ΄ νλΌλ―Έν°μ λμμ΄ λ°λλ€λ©΄?
λ€μκ³Ό κ°μ μν©μμ λμνλΌλ―Έν°νλ₯Ό μ¬μ©νλ©΄ λ°λλ μꡬ μ¬νμ ν¨κ³Όμ μΌλ‘ λμν μ μλ λ©μλλ₯Ό ꡬνν μ μμ΅λλ€. μ΄ 4κ°μ§ λ°©λ²μΌλ‘ λμ νλΌλ―Έν°λ₯Ό ꡬνν΄λ³΄κ³ , λΉκ΅ν΄λ³΄κ² μ΅λλ€!
1οΈβ£ μΆμμ 쑰건μΌλ‘ νν°λ§
μ ν 쑰건μ κ²°μ νλ μΈν°νμ΄μ€ μ μ
public interface ApplePredicate {
boolean test (Apple apple);
}
λ€μν μ ν 쑰건μ λννλ μ¬λ¬ λ²μ μ ApplePredicateλ₯Ό μ μ
// λ¬΄κ±°μ΄ μ¬κ³Ό μ ν
public class AppleHeavyWeightPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
}
// λ
Ήμ μ¬κ³Όλ§ μ ν
public class AppleGreenColorPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return GREEN.equals(apple.getColor());
}
}
μμμ μ μν ApplePredicateλ₯Ό μ΄μ©ν νν° λ©μλ
public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate p) {
List<Apple> result = new ArrayList<>();
for (Apple apple: inventory) {
if ( p.test(apple) ) {
result.add(apple);
}
}
return result;
}
2οΈβ£ μ΅λͺ ν΄λμ€ μ¬μ©
μ΅λͺ ν΄λμ€λ₯Ό μ΄μ©νλ©΄ ν΄λμ€ μ μΈκ³Ό μΈμ€ν΄μ€νλ₯Ό λμμ ν μ μμ΅λλ€.
List<Apple> redApples = filterApples(inventory, new ApplePredicate() {
public boolean test(Apple apple) {
return RED.equals(apple.getColor());
}
});
3οΈβ£ λλ€ ννμ μ¬μ©
λλ€ ννμμ μ¬μ©νλ©΄ μ΅λͺ ν΄λμ€ λ°©μλ³΄λ€ ν¨μ¬ κ°κ²°νκ³ μ§κ΄μ μΌλ‘ ꡬν κ°λ₯ ν©λλ€.
List<Apple> redApples = filterApples(inventory, (Apple apple) -> RED.equals(apple.getColor()));
4οΈβ£ 리μ€νΈ νμμΌλ‘ μΆμν
νμ νλΌλ―Έν°Tλ±μ₯
public interface Predicate<T> {
boolean test(T t);
}
public static <T> List<T> filter(List<T> list, Predicate<T> p) {
List<T> result = new ArrayList<>();
for (T e: list) {
if ( p.test(e) ) {
result.add(e);
}
}
return result;
}
μ¬κ³ΌλΏλ§ μλλΌ λ°λλ, μ€λ μ§, μ μ λ±μ 리μ€νΈμ νν° λ©μλλ₯Ό μ¬μ©ν μ μμ΅λλ€.
List<Apple> redApples = filter(inventory, (Apple apple) -> RED.equals(apple.getColor()));
List<Integer> evenNumbers = filter(numbers, (Integer i) -> i % 2 == 0);
리μ€νΈ νμμΌλ‘ μΆμν λ°©μμ μ΄μ©νλ©΄ μ μ°μ±κ³Ό κ°κ²°ν¨μ λμΌ μ μμ΅λλ€.