ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Chapter 14 람다식 확인문제 정답
    프로그래밍 언어/이것이 자바다 2022. 1. 15. 12:18

    1. 람다식에 대한 설명으로 틀린 것은 무엇입니까?

    ① 람다식은 함수적 인터페이스의 익명 구현 객체를 생성한다.

    ② 매개 변수가 없을 경우 () -> {...} 형태로 작성한다.

    ③ (x,y) -> {return x+y;} 는 (x,y) -> x+y로 바꿀 수 있다.

    ④ @FunctionalInterface가 기술된 인터페이스만 람다식으로 표현이 가능하다.

     

    2. 메소드 참조에 대한 설명으로 틀린 것은 무엇입니까?

    ① 메소드 참조는 함수적 인터페이스의 익명 구현 객체를 생성한다.

    ② 인스턴스 메소드는 "참조변수::메소드"로 기술한다.

    ③ 정적 메소드는 "클래스::메소드"로 기술한다.

    ④ 생성자 참조인 "클래스::new"는 매개 변수가 없는 디폴트 생성자만 호출한다.

     

    3. 잘못 작성된 람다식은 무엇입니까?

    ① a -> a+3

    ② a,b -> a*b

    ③ x -> System.out.println(x/5)

    ④ (x,y) -> Math.max(x,y)

     

    4. 다음 코드는 컴파일 에러가 발생합니다. 그 이유가 무엇입니까?

    import java.util.function.IntSupplier;
    
    public class LambdaExample {
    	public static int method(int x, int y) {
        	IntSupplier supplier = () -> {
            	x *= 10;
                int result = x+y;
                return result;
            };
        }
        int result = supplier.getAsInt();
        return result;
    }

    method 안의 매개변수는 final 특성을 가지기 때문에 값을 변경할 수 없음

     

    5. 다음은 배열 항목 중에 최대값 또는 최소값을 찾는 코드입니다. maxOrMin() 메소드의 매개값을 람다식으로 기술해보세요.

    import java.util.function.IntBinaryOperator;
    
    public class LambdaExample {
    	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) -> {
    				return ((a<=b) ? a : b);
    			}
    		);
    		System.out.println("최소값: " + min);
    	}
    }

     

    6. 다음은 학생의 영어 평균 점수와 수학 평균 점수를 계산하는 코드입니다. avg() 메소드를 선언해보세요.

    import java.util.function.ToIntFunction;
    
    public class LambdaExample {
    	private static Student[] students = {
    		new Student("홍길동", 90, 96),
    		new Student("신용권", 95, 93)
    	};
    	
    	// avg 메소드 작성
    	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());
    	double englishAvg = avg(Student :: getEnglishScore());
    
    double mathAvg = avg(s -> s.getMathScore());
    	double mathAvg = avg(Student :: getMathScore());

    댓글