본문 바로가기

Programming/JAVA

람다식(4) - 표준 API의 함수적 인터페이스 6 : Predicate Functional Interface

JAVA logo image

 

 

Predicate 함수적 인터페이스는, 파라미터의 값을 조사하여 boolean 값을 리턴하는 메서드를 가지고 있습니다. 대부분 testXXXX( ) 형태의 메서드이죠. 이 인터페이스의 추상 메서드들도 한번 아래와 같이 알아보도록 하겠습니다. 

 

인터페이스 명 추상 메서드 설명
Predicate<T> boolean test(T t) 객체 T를 조사한다.
BiPredicate<T, U> boolean test(T t, U u) 객체 T와 U를 비교해 조사한다.
DoublePredicate boolean test(double value) double 값을 조사한다.
IntPredicate boolean test(int value) int 값을 조사한다.
LongPredicate boolean test(long value) long 값을 조사한다.

 

Predicate<T> 인터페이스를 기준으로 간단한 예시를 들어보겠습니다. 추상 메서드 test( )의 경우 파라미터로는 T 객체 하나만을 갖습니다. 그리고 리턴 타입은 boolean이기 때문에 람다식 { } 중괄호 리턴 값 역시 당연하게도 boolean 타입의 값이 됩니다. 오버라이드 하는 추상 메서드의 리턴 값이 당연히 boolean 타입의 값이 되어야 하겠죠.

 

Predicate<Student> predicate = t -> { return t.getSex().equals("남자"); }
Predicate<Student> predicate = t -> t.getSex().equals("남자");

 

위와 같은 간단한 람다식을 작성할 수 있습니다. 여기서 T는 Student 타입으로 지정되었습니다. 그럼 Student 객체의 메서드 getSex( )를 통해 리턴된 값을 equals( )로 조사하여 "남자"일 경우에만 true를 리턴하는 형태로 메서드를 선언했습니다. 

 

 


 

 

public class Student {
	private String name;
	private String sex;
	private int score;
	
	public Student(String name, String sex, int score) {
		this.name = name;
		this.sex = sex;
		this.score = score;
	}
	
	public String getSex() { return sex; }
	public int getScore() { return score; }
}

 

 

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class ExampleMain {
	
	private static List<Student> list = Arrays.asList(
			new Student("스윙스", "남자", 90),
			new Student("재키와이", "여자", 50),
			new Student("블랙넛", "남자", 92),
			new Student("스월비", "여자", 80)
	);
	
	public static double avg( Predicate<Student> predicate ) {
		int count = 0, sum = 0;
		
		for(Student student : list) {
			if( predicate.test(student) ) {
				count++;
				sum += student.getScore();
			}
		}
		
		return (double) sum / count;
	}
	
	public static void main(String[] args) {
		double maleAvg = avg( t -> t.getSex().equals("남자") );
		double femaleAvg = avg( t -> t.getSex().equals("여자") );
		
		System.out.println("남자 평균: " + maleAvg);
		System.out.println("여자 평균: " + femaleAvg);
	}
}

/* 출력
남자 평균: 91.0
여자 평균: 65.0
*/