티스토리 뷰

728x90

 

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

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

	public int getEngScore() {
		return engScore;
	}

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

public class Ex06Function {
	
	//배열선언
	public static List<Ex06Student> list = Arrays.asList(
			new Ex06Student("호니쓰", 95, 100),
			new Ex06Student("이수이", 100, 100)
			);
	
	//메소드 : 이름출력
	public static void printString(Function<Ex06Student, String> fn) {
		for (Ex06Student ex06Student : list) {
			System.out.print(fn.apply(ex06Student)+" ");
		}System.out.println();
	}
	
	//메소드 : 점수 출력
	public static void printInt(ToIntFunction<Ex06Student> fn) {
		for (Ex06Student ex06Student : list) {
			System.out.print(fn.applyAsInt(ex06Student)+" ");
		}System.out.println();
	}
	
	public static void main(String[] args) {
		System.out.println("[이름]");
		printString(t -> t.getName());
		
		System.out.println("[기분]");
		printInt(t -> t.getEngScore());
		
		System.out.println("[허기짐]");
		printInt(t -> t.getMathScore());
	}
}

 

 

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

public class Ex07Function1 {
	//Function
	/*
	 	- 매개변수와 리턴값이 있고, apply~~()메서드를 가진 람다 인터페이스 
	 	- 매개변수와 리턴값 매핑시 사용
	 */

	// 배열선언
	public static List<Ex06Student> list = Arrays.asList(
			new Ex06Student("호니쓰", 95, 100), 
			new Ex06Student("이수이", 100, 100)
			);

	public static double avg(ToIntFunction<Ex06Student> fn) {
		int sum = 0;
		for (Ex06Student ex06Student : list) {
			sum += fn.applyAsInt(ex06Student);
		}
		double avg = (double) sum / list.size();
		return avg;
		
	}

	public static void main(String[] args) {
		double engAvg = avg(s -> s.getEngScore());
		System.out.println("기분 평균 점수 : "+engAvg);
		
		double mathAvg = avg(s -> s.getMathScore());
		System.out.println("허기짐 평균 점수 : "+mathAvg);
	}
	
}​

728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
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
31
글 보관함