티스토리 뷰

JAVA

[JAVA] 람다

PeonyF 2023. 1. 30. 14:50
반응형

람다란 무엇인가?

메소드로 전달할 수 있는 익명 함수를 단순화한것이라고 할 수 있다. 

 

람다예제

불리언 표현식 (List<String>list) -> list.isEmpty()
객체 생성 () -> new Apple(10)
객체에서 소비 (Apple a) -> {System.out.println(a.getWeight());}
객체에서 선택/추출 (String s) -> s.length()
두 값을 조합 (int a, int b) ->a*b
두 객체 비교 (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())

 

기존

Comparator<Apple> byWeight = new Comparator<Apple>(){
	public int compare(Apple a1, Apple a2){
    	return a1.getWeight(0.compareTo(a2.getWeight());
        }
    };

람다 사용

Comparator<Apple> byWeight = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());

 

어디에 어떻게 람다를 사용할까?

List<Apple> greenApples = filter(inventory, (Apple a) -> GREEN.equals(a.getColor());

람다 표현식으로 함수형 인터페이스의 추상 메서드 구현을 직접 전달할 수 있으므로 전체 표현식을 함수형 인터페이스의 인스턴스로 취급할 수 있다.

 

//람다 사용
Runnable r1 = () -> System.out.println("Hello World 1");

//익명 클래스 사용
Runnable r2 = new Runnable(){ 
	public void run(){
    	System.out.println("Hello World 2");
     }
};

public static void process(Runnable r){
	r.run();
}

process(r1);
process(r2);

//람다표현식으로 출력
process(() -> System.out.println("Hello World 3"));

 

메서드 참조

1.정적 메소드 참조 ex.Integer::parseInt

2.다양한 형식의 인스턴스 메서드 참조 ex. String::length

3.기존 객체의 인스턴스 메서드 참조(외부 객체의 메소드 호출시)

ex. Trasaction 객체를 할당받은 expensizeTranszction 지역변수가 있고, Transaction 객체에는 getValue메서드가 있다면,

-> expensiceTransaction::getValue

 

메서드 참조 예제

(Apple apple) -> apple.getWeight() Apple::getWeight
() -> Thred.currentThread()::dumpStack
Thread.currentThreadd().dumpStack()  
(str,i) -> str.substring(i) String::substring
(String s) -> System.out.println(s) (String s)
-> this.isValidName(s)
System.out::println
this::isValidName

 

기존

List<String> str = Arrays.asList("a","b","A","B");

람다표현식

str.sort(String::compareToIgnoreCase);

 

생성자 참조 예제

- 인스턴스화 하지 않고도 생성자에 접근할 수 있다.

Apple(String color, Integer weight)처럼 두 인수를 갖는 생성자는 BiFunction 인터페이스를 가지므로 아래와 같이 바꿀 수 있다.

BiFunction<String,Integer,Apple> c3 = (color,weight) -> new Apple(color, weight);
Apple a3 = c3.apply(GREEN,110);

 

Comparator 조합

- 역정렬

inventory.sort(comparing(Apple::getWeight).reversed());

- 비교정렬이 2개 일때 

inventory.sort(comparing(Apple::getWeight)
	 .reversed()
         .thenComparing(Apple::getConutry));

 

출저 : 모던 자바 인 액션

 

반응형

'JAVA' 카테고리의 다른 글

[JAVA] 객체 지향의 특징 4가지  (0) 2023.02.23
[JAVA] 인터페이스  (0) 2023.02.23
자바 문자열 파싱(parsing) : StringTokenizer  (0) 2023.01.27
[JAVA] JVM  (0) 2023.01.14
[JAVA] 객체지향설계 5원칙 - SOLID  (0) 2022.11.07
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함