Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 코딩입문
- 코딩초보자
- IdeaPad 3 15ABA7
- 레노버 아이디어패드 슬림3
- 코린이
- 데이터베이스 JOIN
- 데이터베이스 DELETE
- 슬림3
- 자바입문
- 데이터베이스기초
- 오라클 DELETE
- 오라클UPDATE
- 레노버 노트북
- 개발자준비
- 자바초보
- 오라클
- 가성비 노트북
- SQL
- 사무용 노트북
- 데이터베이스 집합연산자
- 코딩일기
- 데이터베이스
- lenovo ideapad 3
- 데이터베이스 UPDATE
- 라이젠노트북
- 티모장인
- 데이터베이스 예제
- 데이터베이스 기초
- 레노버 슬림3
- 탑마이장인
Archives
- Today
- Total
스퐁지송 개발노트
22.12.05(월) 람다식 Operator, Predicate 본문
728x90
Operator : (매개변수) 와 return(리턴)을 같이 사용
package 람다;
import java.util.function.BinaryOperator;
import java.util.function.DoubleBinaryOperator;
import java.util.function.IntBinaryOperator;
import java.util.function.IntUnaryOperator;
import java.util.function.UnaryOperator;
public class Sample01 {
public static void main(String[] args) {
//실수람다식
BinaryOperator<Double> bo = (a, b) -> a + b;
System.out.println(bo.apply(3.5, 16.3));
UnaryOperator<Double> uo = (a) -> a + 10; //단항식람다식
System.out.println(uo.apply(3.14));
DoubleBinaryOperator dbo = (a,b) -> a * b; //Binary = 이항식
//두개의 값을 넣어 람다식을 실행
System.out.println(dbo.applyAsDouble(1.4, 2.5));
//정수람다식
IntUnaryOperator iuo = (x)->{ //Unary = 단항식
System.out.println("iuo 람다 실행");
return x+10;
};
System.out.println(iuo.applyAsInt(10));
//2개의 정수를 받아서 큰값을 출력
IntBinaryOperator ibo = (x,y) -> {
//구현식 넣기
if(x > y) {
return x;
}else {
return y;
}
};
System.out.println(ibo.applyAsInt(55, 123123));
}
}
결과
19.8
13.14
3.5
iuo 람다 실행
20
123123
람다식을 이용 최대값 최소값 구하기
package 람다;
import java.util.function.IntBinaryOperator;
public class Sample02 {
// 정적변수
static int[] scores = { 92, 93, 78 };
//Operator : 매개변수도 있고(몇개든) 리턴도 있음
static int maxOrMin(IntBinaryOperator operator) {
int result = scores[0];
// 향상된 for문
for (int score : scores) {
result = operator.applyAsInt(score, result);
}
return result;
}
public static void main(String[] args) {
// 람다식(score,result) -> (a,b)
// 최대값 구하기
int max = maxOrMin((a, b) -> { //if문을 이용해 a or b값을 위 maxOrMin에 값을 넣어줌
if (a > b) {
return a;
} else {
return b;
}
}
);
System.out.println("최대값 : " + max); //max = maxOrMin으로 설정 max에 if문의 값이 입력
// 람다식(score,result) -> (a,b)
// 최소값 구하기
int min = maxOrMin((a, b) -> {
if (a < b) {
return b;
} else {
return a;
}
}
);
System.out.println("최소값 : " + min);
}
}
Predicate
매개변수: o
리턴 값 : boolean
정수형 : IntPredicate
실수형 : DoublePredicate
package 람다;
import java.util.function.Predicate;
public class Sample03 {
public static void main(String[] args) {
// 10 이상이면 True , 아니면 False
Predicate<Integer> p = (a) -> {
if (a >= 10) {
return true;
} else {
return false;
}
};
System.out.println(p.test(15));
if (p.test(15))
System.out.println("10이상입니다.");
else
System.out.println("10 미만 입니다.");
}
}
예시
컴공과 학생의 영어 점수 평균, 수학 점수 합계
통계과 인원수 구하기
메인문
package 람다;
import java.util.List;
import java.util.function.Predicate;
public class Student_Main {
static Student[] list = { new Student("티모", 90, 80, "컴공"),
new Student("마스터이", 95, 70, "통계"),
new Student("릴리야", 100, 60, "컴공"),
new Student("가렌", 70, 60, "통계"),
new Student("사일러스", 55, 20, "컴공"),
new Student("베인", 100, 90, "컴공"),
};
static double avgEng(Predicate<Student> a) {
int count = 0;
int sum = 0;
/* 영어점수의 평균 */
// 1번반복 -> Student티모 객체,2번반복 -> Student 마스터이 객체....
for (Student A : list) {
if (a.test(A)) { // 실행했을때 리턴되는값은 true/false만 리턴
count++; // 평균을 구하는 것이기때문에 list의 배열방만큼 반복
sum += A.getEng();
}
}
return (double) sum / count; //count에는 배열방만큼의 수가 누적
}
/* 수학 점수의 합계 */
static int sumMath(Predicate<Student> b) {
int sum = 0;
for (Student B : list) {
if (b.test(B)) { // 실행했을때 리턴되는값은 true/false만 리턴
sum += B.getMath();
}
}
return sum;
}
/* major가 통계인 사람수 */
static int cnt(Predicate<Student> c) {
int count = 0;
for (Student C : list) {
if (c.test(C)) {
count++; // True일때 카운트 갯수 증가
}
}
return count;
}
public static void main(String[] args) {
/* 영어점수 평균 출력하기 */
double avg;
avg = avgEng(t -> t.getMajor().equals("컴공"));
// t.getMajor().equals("컴공") = Majo가"컴공"과 같은 객체를 가져와라~
// == Predicate<Student> p = (t) -> t.getMajor().equals("컴공")
System.out.println(avg);
/* 수학점수 합계 출력하기 */
int sum;
sum = sumMath(t -> t.getMajor().equals("컴공"));
System.out.println(sum);
/* 통계과 인원수 구하기 */
int count;
count = cnt(t -> t.getMajor().equals("통계"));
System.out.println(count);
}
}
서브문
package 람다;
public class Student {
String name;
int eng;
int math;
String major;
public Student(String name, int eng, int math, String major) {
this.name = name;
this.eng = eng;
this.math = math;
this.major = major;
}
public String getName() {
return name;
}
public int getEng() {
return eng;
}
public int getMath() {
return math;
}
public String getMajor() {
return major;
}
}
결과
86.25
250
2
728x90
'JAVA 입문 시작' 카테고리의 다른 글
22.12.05(월) 스트림 (0) | 2022.12.05 |
---|---|
22.12.05(월) andThen과 compose (0) | 2022.12.05 |
22.12.02(불금) 자바안의 기본 람다 인터페이스 구현으로 예시문작성 (0) | 2022.12.02 |
22.12.02(불금) 자바안의 기본 람다 인터페이스 구현 (0) | 2022.12.02 |
22.12.02(불금) 람다식 (익명함수) (0) | 2022.12.02 |
Comments