0707 JAVA
IntSupplier intSupplier = () -> { int num = (int) (Math.random() * 6) + 1; return num; };
- int num 값을 리턴
int num = intSupplier.getAsInt();
Function<T, R> --- R apply(T t) --> 객체 T를 객체 R로 매핑해서 달라! ToIntFunction<T> --- int applyAsInt(T t) --> 객체 T를 int로 매핑
//지역변수로 Function<T, R> 타입의 변수를 선언하였습니다.
Function<Student, String> func;
//추상메소드의 시그니처
// R apply(T t); ====> String apply(Student studnet)
func = (Student student) -> {
return student.getName();
};
//위의 람다식 생략조건 적용 하면
func = student -> student.getName();
//변수명 또한 더 간략하세 적용하면
func = s -> s.getName();
String name = func.apply(new Student("홍길동", 80, 77));
log.info("- name : " + name);
- IntBinaryOperator ----> 두 개의 int 연산
- 매개변수 타입이, java.util.function패키지의 IntBinaryOperator 함수적 인터페이스 타입임.
- 이 함수적 인터페이스는 2개의 int 값을 입력으로 줄테니, int 값 하나를 반환하라!는 추상메소드를. 가지고 있음
- 이 추상메소드는 : int applyAsInt(int left, int right);
ex)
//이 메소드는 배열의 원소중에, 최소 또는 최대값을 반환하는 기능을 수행하는 메소드임.
public static int maxOrMin(IntBinaryOperator operator) {
int result = scores[0]; //배열의 첫 번째 원소
for(int score : scores) {
//우리가 던진 람다식의 블록 내의 구현에서,
//큰 값/또는 작은 값을 반환하도록 구현
result = operator.applyAsInt(result, score);
}//enhanced for
return result;
}//maxOrMin
public static void main(String[] args) {
//--1. 최대값 얻기
int max = maxOrMin( (a, b) -> {
if(a >= b) {
return a;
}
else {
return b;
}//if-else
} //람다식을 통한 익명구현객체 생성 및 전달
); //maxOrMin
log.info("최대값 : " + max);
}//main
//리스트에 있는 모든 학생들의 평균점수를 구해서 반환
private static double avg(Predicate<Student> predicate) {
int count = 0;
int sum =0;
//리스트의 모든 요소 순회(traverse)
for(Student student : list) {
//조건 검사(test)
if(predicate.test(student)) { // if ture 라면 ...
count++;
sum += student.getScore();
}//if
}//enhanced for
return (double) sum / count; //산술평균구해서 반환
}//avg
public static void main(String[] args) {
double maleAvg = avg( t -> t.getSex().equals("남자"));
log.info("남자 평균 점수 : " + maleAvg);
double femaleAvg = avg( t -> t.getSex().equals("여자"));
log.info("여자 평균 점수 : " + femaleAvg);
}//main