람다 표현식이란?
람다 표현식은 메서드로 전달할 수 있는 익명 함수를 단순화한 것이라고 할 수 있다. 람다 표현식은 함수형 인터페이스를 구현하는 방법으로만 사용 가능하다.
함수형 인터페이스
public Interface Runnable {
void run();
}
위의 Runnable 인터페이스와 같이 인터페이스 내에 추상 메서드가 딱 하나 있을때 함수형 인터페이스라고 부른다.
자바에서는 다양한 함수형 인터페이스를 제공해준다. 대표적인 함수형 인터페이스들을 구현해보았다.
1. void -> void
Runnable r = () -> System.out.println("runnable!")
r.run()
2. void -> T
Supplier<String> supplier = () -> "hello".toUpperCase();
String result = supplier.get();
3. (T,K) -> K
Function<String,String> func = (String str) -> str.toUpperCase();
String result = func.apply("function!");
Function<String,String> func2 = String::toUpperCase;
String result2 = func2.apply("function2!");
4. (T) -> Boolean
Predicate<Integer> predicate = (Integer i) -> i > 10;
boolean predicateResult = predicate.test(8);
5. 객체 생성
Function<String,Person> personFunction = (String str2) -> new Jemin(str2);
Person person = personFunction.apply("jemin");
Function<String,Person> personFunction2 = Person::new;
Person person2 = personFunction2.apply("jemin");
public static class Person {
String name;
public Person(String name)
{
this.name = name;
}