UniCode
[이것이 자바다]CH14.람다식(확인문제풀이) 본문
01. 람다식에 대한 설명으로 틀린 것은 무엇입니까?
① 람다식은 함수적 인터페이스의 익명 구현 객체를 생성한다.
② 매개 변수가 없을 경우 ( ) -> { ... } 형태로 작성한다.
③ (x , y) -> { return x+y; }는 (x , y) -> x+y로 바꿀 수 있다.
④ @FunctionalInterface가 기술된 인터페이스만 람다식으로 표현이 가능하다.
☞ ④ @FunctionalInterface가 기술된 인터페이스만 람다식으로 표현이 가능하다.
어노테이션이 기술 되어 있지 않아도 하나의 추상 메소드만 선언된 인터페이스는 모두 람다식 표현이 가능하다.
02. 메소드 참조에 대한 설명으로 틀린 것은?
① 메소드 참조는 함수적 인터페이스의 익명 구현 객체를 생성한다.
② 인스턴스 메소드는 "참조변수::메소드"로 기술한다.
③ 정적 메소드는 "클래스::메소드"로 기술한다.
④ 생성자 참조인 "클래스::new"는 매개 변수가 없는 디폴트 생성자만 호출한다.
☞ ④ 생성자 참조인 "클래스::new"는 매개 변수가 없는 디폴트 생성자만 호출한다.
생성자가 오버로딩되어 여러 개가 있을 경우, 컴파일러는 함수적 인터페이스의 추상 메소드와 동일한 매개 변수 타입과 개수를 가지고 있는 생성자를 찾아서 실행한다.
03. 잘못 작성된 람다식은 무엇입니까?
① a -> a+3
② a, b -> a*b
③ x -> System.out.println(x/5)
④ (x , y) -> Math.max(x, y)
☞ ② a, b -> a*b (X) (a,b) -> a*b (O)
람다식 작성 시 매개 변수가 1개 일 때만 ( )를 생략할 수 있다.
실행부 작성 시 return문 한 문장만 존재할 경우 { }를 생략할 수 있다.
4. 다음 코드는 컴파일 에러가 발생합니다. 그 이유가 무엇입니까?
import java.util.function.IntSupplier;
public class LamdaExample {
public static int method( int x, int y) {
IntSupplier supplier = () -> {
//int x *= 10;
//int result = x+y;
// 람다식 안에 선언된 매개변수와 로컬 변수는 final 특성을 가지고 있어 데이터 변경이 불가능
int x1 = x * 10;
int result = x1 + y;
return result;
};
int result = supplier.getAsInt();
return result;
}
public static void main(String[] args) {
System.out.println(method(3,5));
}
}
05. 다음은 배열 항목 중에 최대값 또는 최소값을 찾는 코드입니다. maxOrMin() 메소드의 매개값을 람다식으로 기술해보세요.
import java.util.function.IntBinaryOperator;
public class LamdaExample {
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)-> (a>=b)?a:b);
System.out.println("최대값 : " + max);
//익명 객체 구현
max = maxOrMin(new IntBinaryOperator() {
@Override
public int applyAsInt(int a, int b) {
return (a>b)? a:b;
}
});
int min = maxOrMin((a,b) -> (a<b)?a:b);
System.out.println("최소값 : " + min);
}
}
06. 다음은 학생의 영어 평균 점수와 수학 평균 점수를 계산하는 코드입니다. avg() 메소드를 선언해보세요.
import java.util.function.ToIntFunction;
public class LamdaExample {
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. 6번의 main() 메소드에서 avg()를 호출할 때 매개값으로 준 람다식을 메소드 참조로 변경해보세요.
double englishAvg = avg( s -> s.getEnglishScore() );
> 1)
double mathAvg = avg( s -> s.getMathScore() );
> 2)
☞ 1)double englishAvg = avg( Student :: getEnglishScore);
2) double mathAvg= avg( Student :: getMathScore);
'이것이 자바다' 카테고리의 다른 글
[이것이 자바다]CH15.컬렉션 프레임워크(확인문제풀이) (1) | 2021.05.29 |
---|---|
[이것이 자바다]CH13.제네릭(확인문제풀이) (0) | 2021.05.16 |
[이것이 자바다]CH12.멀티 스레드(확인문제풀이) (0) | 2021.05.15 |
[이것이 자바다] BankApplication (클래스메소드+예외처리) (0) | 2021.05.08 |
[이것이 자바다]CH10.예외처리(확인문제풀이) (0) | 2021.05.05 |