Skip to content

Instantly share code, notes, and snippets.

View hongbeomi's full-sized avatar
🏃‍♂️
Slowly And Steadily

ian.0701(이안) hongbeomi

🏃‍♂️
Slowly And Steadily
View GitHub Profile
enum Color { RED, GREEN }
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, Color color) {
List<Apple> result = new ArrayList<>();
for (Apple apple: inventory) {
if ( apple.getColor().equals(color) ) {
result.add(apple);
}
}
return result;
}
// 구현한 메서드를 호출하기
// 모든 속성을 메서드 파라미터로 추가한 모습 (끔찍)
public static List<Apple> filterApples(List<Apple> inventory, Color color, int weight, boolean flag) {
List<Apple> result = new ArrayList<>();
for (Apple apple: inventory) {
if ( (flag && apple.getColor().equals(color)) || (!flag && apple.getWeight() > weight) ){
result.add(apple);
}
}
return result;
}
// 선택 조건을 결정하는 인터페이스 정의
public interface ApplePredicate{
boolean test (Apple apple);
}
// 무거운 사과만 선택
public class AppleHeavyWeightPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
// 프레디케이트 객체로 사과 검사 조건을 캡슐화하기
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;
}
// 무거운 사과 선택
public class AppleHeavyWeightPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
}
// 녹색 사과 선택
public class AppleGreenColorPredicate implements ApplePredicate {
// filterApples 메서드의 동작을 직접 파라미터화 했다.
List<Apple> redApples = filterApples(inventory, new ApplePredicate() {
public boolean test(Apple apple){
return RED.equals(apple.getColor());
}
});
// 이벤트 핸들러 객체를 구현하는 익명 클래스
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Whoooo a click!!");
// 람다 표현식을 이용해서 위 예제 코드를 간단하게 재구현하였다!
List<Apple> result = filterApples(inventory, (Apple apple) -> RED.equals(apple.getColor()));
// 리스트 형식으로 추상화!
public interface Predicate<T> {
boolean test(T t);
}
public static <T> List<T> filter(List<T> list, Predicate<T> p) { // 형식 파라미터 T
List<T> result = new ArrayList<>();
for(T e: list) {
if(p.test(e)) {
result.add(e);
// 리스트 형식으로 추상화!
public interface Predicate<T> {
boolean test(T t);
}
public static <T> List<T> filter(List<T> list, Predicate<T> p) { // 형식 파라미터 T
List<T> result = new ArrayList<>();
for(T e: list) {
if(p.test(e)) {
result.add(e);