티스토리 뷰

728x90
public class Ex09Student {
	// 필드 선언
	private String name;
	private String gender;

	private int engScore;
	private int mathScore;

	// 매개변수 있는 생성자
	public Ex09Student(String name, int engScore, int mathScore) {
		// TODO Auto-generated constructor stub
		super();
		this.name = name;
		this.engScore = engScore;
		this.mathScore = mathScore;
	}

	public Ex09Student(String name, String gender, int engScore, int mathScore) {
		// TODO Auto-generated constructor stub
		super();
		this.name = name;
		this.gender = gender;
		this.engScore = engScore;
		this.mathScore = mathScore;
	}

	// Getter만 생성
	public String getName() {
		return name;
	}

	public String getGender() {
		return gender;
	}

	public int getEngScore() {
		return engScore;
	}

	public int getMathScore() {
		return mathScore;
	}
}
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Ex09Predicate {
	//Predicate
	/*
	 	- 매개변수와 리턴값 있는 람다 인터페이스
	 	- 메서드 : text~()
	 	- 매개변수 값을 통해 boolean 값을 리턴하는 역할
	 */
	private static List<Ex09Student> list = Arrays.asList(
			new Ex09Student("호니", "여자", 95, 100),
			new Ex09Student("몽자", "여자", 100, 92),
			new Ex09Student("맛나", "감자", 80, 75),
			new Ex09Student("나는", "감자", 78, 92)
			);
	
	public static double avg(Predicate<Ex09Student> pr) {
		int count = 0, sum = 0;
		for (Ex09Student ex09Student : list) {
			if(pr.test(ex09Student)) {
				count++;
				sum += ex09Student.getEngScore();
			}
		}
		return (double) sum / count;
	}
	
	public static void main(String[] args) {
		double femaleAvg = avg(t -> t.getGender().equals("여자"));
		System.out.println("여자 평균 점수 : "+femaleAvg);
		//여자 평균 점수 : 97.5
		
		double potatoAvg = avg(t -> t.getGender().equals("감자"));
		System.out.println("감자 평균 점수 : "+potatoAvg);
		//감자 평균 점수 : 79.0
	}
}

728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/09   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함