
람다식 작성하기

람다식 작하기 - 주의사항

함수형 인터페이스




java.util.function패키지





Function의 합성


Predicate의 결합

메서드 참조(method reference)


[출처]자바의 정석
실습을 해보자.
package chap_21;
import java.util.ArrayList;
import java.util.function.Consumer;
public class _04_Lambda {
public static void main(String[] args) {
/* 람다식(Lambda) + 스트림(Stream) => 람다와 스트림 묶어서 많이씀
* 람대식 : 익명함수와 비슷한 용어(함수보다 단순하게 표현하는 방식)
* 함수의 구현과 호출만으로 프로그래밍이 수행되는 방식
* 외부자료의 부수적인 영향을(side effect)를 주지 않도록 구현하는 방식
* (매개변수) -> { 구현 };
* (int x, int y) -> { return x + y }; => 가능
* int x -> { return x !x; }; => 가능
* int x -> return !x; => 오류
*
* { 리턴이 있다면 } {} : 생략불가
* 실행문이 하나라면 {} 생략가능
* n -> System.out.println(n); => 가능
*/
// ArrayList에 10 20 30 40 50을 입력한 후 출력
ArrayList<Integer> number = new ArrayList<>();
number.add(10);
number.add(20);
number.add(30);
number.add(40);
number.add(50);
for (Integer i : number) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("----람다식----");
// 람다식 형태로 출력
Consumer<Integer> method = (n) ->{
System.out.print(n + " ");
};
number.forEach(method);
System.out.println();
System.out.println("---다른 방법---");
// 다른 방법
number.forEach((n) ->{
System.out.print(n + " ");
});
}
}
package chap_21;
import java.util.HashMap;
public class _05_Lambda2 {
public static void main(String[] args) {
/* Map을 구성하여 forEach를 이용하여 출력
* number.forEach((n)->{
* System.out.println(n + " );
* });
*/
HashMap<String, Integer> map = new HashMap<>();
map.put("철수", 80);
map.put("영희", 90);
map.put("길동", 80);
map.put("철이", 100);
map.put("영수", 88);
map.forEach((x, y) -> System.out.println(x + ": " + y));
Number add = (a, b) -> { // 함수구현
return a + b;
};
System.out.println(add.add(10, 20)); // 결과 체크
Number max = (a, b) -> (a >= b)? a : b;
System.out.println(max.add(10, 20));
}
}
// 람다식에서 사용할 함수형 인터페이스
// 메서드가 1개여야 함. 어노테이션 필수
@FunctionalInterface
interface Number{
int add(int a, int b);
}
'Java 공부 기록' 카테고리의 다른 글
| Math 클래스 (0) | 2024.01.16 |
|---|---|
| 스트림(Stream) (0) | 2023.06.27 |
| 지네릭(Generics), 열거형(enum) (0) | 2023.06.27 |
| 컬렉션 프레임(collections framework) (0) | 2023.06.20 |
| 다형성(Polymorphism) (0) | 2023.06.19 |