(기초)그래서 뭘 배운거야?/Java
JV-64-API-Function : 매개변수 있고, 리턴 값 있고, apply~() 추메 가진 매핑 인페
Soheny.P
2021. 11. 18. 17:40
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