Java 람다와 최신기법을 듣고 람다와 스트림의 사용법을 정리한다.
람다와 스트림의 문법과 사용법을 다루겠다.
java 7에서 8로 넘어오면서 크게 변한 것이 함수형 프로그래밍의 도입이다.
크게 5가지가 있지만 여기선 Lambda와 Stream을 중점적으로 볼 것이다. 나머지 내용은 첨부파일을 참고 바란다.



예를 들어 Apple이란 객체에 함수를 호출 구현한다면, 람다를 사용해 아래의 코드처럼 사용할 수 있다.
// Predicate interface test Method 참조
@FunctionalInterface
interface ApplePredicate<Apple> {
public boolean test(Apple a);
}
//------------------------------------
public static List<Apple> filter(List<Apple> inventory, ApplePredicate<Apple> p) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}
//------------------------------------
List<Apple> inventory =
Arrays.asList(new Apple(80, "green"),
new Apple(155, "green"),
new Apple(120, "red"));
/*
filter method
*/
List<Apple> appleList = filter(inventory, new ApplePredicate<Apple>() {
@Override
public boolean test(Apple apple) {
return apple.getColor().equals("red");
}
});
/*
lambda
*/
appleList = filter(inventory, apple -> apple.getColor().equals("red"));
다른 예로는 정렬을 할 때 사용할 수 있다.