반응형
Preface
이번 확인문제는 본문에 있던 예제 코드가 그대로 나왔다.
람다식을 제대로 사용하려면 함수적 인터페이스에서 제공하는 메소드의 사용법을 정확히 익혀야 할 것 같다.
- 4번: 람다식 안에서 선언된 변수는 final 특성을 지니므로 값을 변경할 수 없다.
- 5번
package ch14;
import java.util.function.IntBinaryOperator;
public class Exercise5 {
private static int[] scores = { 10, 50, 3 };
public static int maxOrMin(IntBinaryOperator operator) {
int result = scores[0];
for (int score : scores) {
result = operator.applyAsInt(result, score);
}
return result;
}
public static void main(String[] args) {
int max = maxOrMin((a, b) -> {
if (a >= b) {
return a;
} else {
return b;
}
});
System.out.println("최대값: " + max);
int min = maxOrMin((a, b) -> {
if (a <= b) {
return a;
} else {
return b;
}
}
);
System.out.println("최소값: " + min);
}
}
- 6번
package ch14;
import java.util.function.ToIntFunction;
public class Exercise6 {
private static Student[] students = { new Student("홍길동", 90, 96), new Student("신용권", 95, 93) };
public static double avg(ToIntFunction<Student> function) {
int sum = 0;
for (Student student : students) {
sum += function.applyAsInt(student);
}
double avg = (double) sum / students.length;
return avg;
}
public static void main(String[] args) {
double englishAvg = avg(s -> s.getEnglishScore());
System.out.println("영어 평균 점수 : " + englishAvg);
double mathAvg = avg(s -> s.getMathScore());
System.out.println("수학 평균 점수 : " + mathAvg);
}
public static class Student {
private String name;
private int englishScore;
private int mathScore;
public Student(String name, int englishScore, int mathScore) {
this.name = name;
this.englishScore = englishScore;
this.mathScore = mathScore;
}
public String getName() {
return name;
}
public int getEnglishScore() {
return englishScore;
}
public int getMathScore() {
return mathScore;
}
}
}
- 7번
double englishAvg = avg( s -> s.getEnglishScore() );
> double englishAvg = avg( Student :: getEnglishScore);
double mathAvg = avg( s -> s.getMathScore() );
> double mathAvg= avg( Student :: getMathScore);
728x90
반응형
'Java > 이것이 자바다' 카테고리의 다른 글
이자바 15장(컬렉션 프레임워크) 확인문제 (0) | 2023.05.02 |
---|---|
컬렉션 프레임워크 (0) | 2023.05.02 |
람다식 (0) | 2023.04.27 |
이자바 13장(제네릭) 확인문제 (0) | 2023.04.26 |
제네릭 (0) | 2023.04.25 |
댓글