Java
람다 표현식
Kabby
2019. 8. 11. 20:42
람다 표현식은 메서드로 전달할 수 있는 익명 함수를 단순화한 것이라고 할 수 있다.
그래서 람다식에는 이름은 없지만, 파라미터 리스트, 바디, 반환 형식, 발생할 수 있는 예외 리스트를 가질 수 있다.
람다의 특징
1. 익명 : 보통의 메서드와 달리 이름이 없으므로 익명으로 표현한다. 구현해야 할 코드에 대한 걱정거리가 줄어든다.
2. 함수 : 람다는 메서드처럼 특정 클래스에 종속되지 않으므로 함수라고 부른다. 하지만 메서드처럼 파라미터 리스트, 바디, 반환 형식, 가능한 예외 리스트를 포함한다.
3. 전달 : 람다 표현식을 메서드 인수로 전달하거나 변수로 저장할 수 있다.
4. 간결성 : 익명 클래스처럼 많은 자질구레한 코드를 구현할 필요가 없다.
람다 표현식은 파라미터, 화살표, 바디로 이루어진다.
(Person s1, Person s2) -> s1.getAge().compareTo(s2.getAge());
파라미터 화살표 람다 바디
람다의 기본 문법
(parameters) -> expression
(parameters) -> { statements; }
Tip. 람다 표현식에서 바디부분에는 return이 함축되어 있으므로 return 문을 명시적으로 사용하지 않아도 된다.
Apple.class
public class Apple{
private int weight = 0;
private Color color;
public Apple(int weight, Color color) {
this.weight = weight;
this.color = color;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@Override
public String toString() {
return String.format("Apple{color=%s, weight=%d}", color, weight);
}
}
LamdaSample.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class LamdaSample {
public static void main(String[] args) {
List<Apple> inventory = Arrays.asList(new Apple(80, Color.GREEN), new Apple(155, Color.GREEN),
new Apple(120, Color.RED));
List<Apple> greenApple = filter(inventory, (Apple a) -> a.getColor() == Color.GREEN);
System.out.println(greenApple);
/*
* 결과값 : [Apple{color=GREEN, weight=80}, Apple{color=GREEN, weight=155}]
*/
Comparator<Apple> c = (Apple a1, Apple a2) -> a1.getWeight() - a2.getWeight();
inventory.sort(c);
System.out.println(inventory);
/*
* 결과값 : [Apple{color=GREEN, weight=80}, Apple{color=RED, weight=120}, Apple{color=GREEN, weight=155}]
*/
}
public static List<Apple> filter(List<Apple> inventory, ApplePredicate p) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}
interface ApplePredicate {
boolean test(Apple a);
}
}