Class별 설명 :
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
Predicate는 함수형 인터페이스로, test(T t) 메서드를 통해 특정 조건을 만족하는지 여부를 검사합니다. @FunctionalInterface 어노테이션은 이 인터페이스가 함수형 인터페이스임을 명시합니다.
public class FilterClass {
public <T> List<T> filter(List<T> list, Predicate<T> p) {
List<T> results = new ArrayList<>();
for (T t : list) {
if (p.test(t)) {
results.add(t);
}
}
return results;
}
}
FilterClass는 리스트를 받아 Predicate 조건을 만족하는 요소들만을 필터링하는 역할을 합니다. filter 메서드는 제네릭 타입 <T>를 사용하여 다양한 타입의 리스트를 처리할 수 있습니다.
public enum Type {
RED, BLUE, BLACK, YELLOW;
}
Type은 열거형으로, 사과의 타입을 정의합니다. RED, BLUE, BLACK, YELLOW 네 가지 타입이 있습니다.
public class Apple {
private int weight;
private Type type;
public Apple(int weight, Type type) {
this.weight = weight;
this.type = type;
}
public int getWeight() {
return weight;
}
public Type getType() {
return type;
}
public void setWeight(int weight) {
this.weight = weight;
}
public void setType(Type type) {
this.type = type;
}
@Override
public String toString() {
return "Apple [weight=" + weight + ", type=" + type + "]";
}
}
Apple 클래스는 사과 객체를 정의합니다. weight와 type 필드를 가지고 있으며, 각각 사과의 무게와 종류를 나타냅니다. 생성자와 게터, 세터 메서드를 통해 사과 객체를 생성하고 조작할 수 있습니다. toString() 메서드는 사과 객체의 문자열 표현을 반환합니다.
public class Main {
public static void main(String[] args) {
FilterClass Flag = new FilterClass();
List<Apple> inventory = List.of(
new Apple(100, Type.RED),
new Apple(120, Type.BLUE),
new Apple(140, Type.BLACK),
new Apple(160, Type.YELLOW)
);
// 색상, 무게 필터 테스트
List<Apple> getRedApple = Flag.filter(inventory, (Apple apple) -> Type.RED.equals(apple.getType()));
List<Apple> getWeight = Flag.filter(inventory, (Apple apple) -> apple.getWeight() == 160);
System.out.println(getRedApple);
System.out.println(getWeight);
//FilterClass 다양한 타입 필터 테스트
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = Flag.filter(numbers, (Integer number) -> number % 2 == 0);
System.out.println(evenNumbers);
}
}
Main 클래스는 프로그램의 시작점입니다. FilterClass 인스턴스를 생성하고, 다양한 사과 객체로 구성된 inventory 리스트를 생성합니다. filter 메서드를 사용하여 타입이 RED인 사과만을 필터링하고, 필터링된 결과를 출력합니다.

Class별 요약 :
- Predicate<T>: 조건을 검사하는 함수형 인터페이스.
- FilterClass: 리스트에서 조건을 만족하는 요소를 필터링.
- Type: 사과의 타입을 정의하는 열거형.
- Apple: 사과 객체를 정의하고 관리.
- Main: 프로그램을 실행하고 필터링 작업을 수행.
참고자료 : 모던자바인액션
'Java' 카테고리의 다른 글
| 비트 연산 (2) | 2025.01.31 |
|---|---|
| Java 빌더 패턴 (Builder Pattern) (0) | 2025.01.29 |
| Java List.of() (1) | 2025.01.26 |
| JAVA 배열 index값 반환 메서드 (2) | 2025.01.25 |
| JDBC, JPA, MyBatis, jOOQ: 데이터베이스 기술 비교 (0) | 2024.08.10 |