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

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

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

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

@FunctionalInterface가 기술된 인터페이스만 람다식으로 표현이 가능하다. -> 선택사항

 

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

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

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

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

생성자 참조인 "클래스::new"는 매개 변수가 없는 디폴트 생성자만 호출한다. -> 생성자가 오버로딩되어 여러 개가 있을 경우, 컴파일러는 함수적 인터페이스의 추상 메소드와 동일한 매개 변수 타입과 개수를 가지고 있는 생성자를 찾아 실행

 

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

① a - > a+3

a, b -> a * b -> (a, b) -> a * b

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

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

 

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

package exercise.Exercise04;

import java.util.function.IntSupplier;

public class LambdaExample {
	public static int method(int x, int y) {
		IntSupplier supplier = () -> {
			//x += 10; //람다식 메소드의 매개변수, 로컬변수는 final 특성을 가져야 한다. 즉, 람다식 내/외부에서 해당값을 변경할 수 없다.
			int result = x + y;
			return result;
		};
		int result = supplier.getAsInt();
		return result;
	}
}

 

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

package exercise.Exercise05;

import java.util.function.IntBinaryOperator;

public class LambdaExample {
	public 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);
	}
}
최대값: 50
최소값: 3

 

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

package exercise.Exercise06;

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;
		}
	}
}
영어 평균 점수: 92.5
수학 평균 점수: 94.5

 

7. 6번의 main() 메소드에서 avg() 를 호출할 때 매개값으로 준 람다식을 메소드 참조로 변경해보세요.

package exercise.Exercise07;

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());
		double englishAvg = avg ( Student::getEnglishScore ); //매개변수의 타입 :: 메소드명
		System.out.println("영어 평균 점수: " + englishAvg);
		
		//double mathAvg = avg ( s -> s.getMathScore());
		double mathAvg = avg ( Student::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;
		}
	}
}
영어 평균 점수: 92.5
수학 평균 점수: 94.5

+ Recent posts