public static List<Apple> filterGreenApples(List<Apple> inventory) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if ("green".equals(apple.getColor())) {
result.add(apple);
}
}
return result;
}
public static List<Apple> filterApplesByColor(List<Apple> inventory, String color) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (color.equals(apple.getColor())) {
result.add(apple);
}
}
return result;
}
public static List<Apple> filterApples(List<Apple> inventory, String color, int weight, boolean flag) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if ((flag && color.equals(apple.getColor())) ||
(!flag && apple.getWeight() > weight)) {
result.add(apple);
}
}
return result;
}
단순히 매개변수를 늘리는 방식이 아닌, 요구사항 변화에 유연하게 대응할 방법 필요.
Predicate 인터페이스
true / false 반환.전략 디자인 패턴
따라서, 메서드는 다양한 동작(전략)을 인수로 받아 내부적으로 실행 가능해야 함.
public interface ApplePredicate {
boolean test(Apple apple);
}
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;
}
List<Apple> redApples = filterApples(inventory, new ApplePredicate() {
@Override
public boolean test(Apple apple) {
return "red".equals(apple.getColor());
}
});
List<Apple> redApples = filterApples(inventory, apple -> "red".equals(apple.getColor()));
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;
}
inventory.sort((a1, a2) -> a1.getWeight().compareTo(a2.getWeight()));
Thread t = new Thread(() -> System.out.println("Hello from another thread!"));
t.start();
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> result = executor.submit(() -> 42);
ExecutorService + Callable