Runnable t = new Runnable() {
public void run() {
// 코드
}
}
위 코드를 람다식으로 표현하면
Runnable t = () -> { //코드 "};
(타입 매개변수 [, ...]) -> { 실행문; ...};
(a, b) -> { return a+b;}; 처럼 return만 존재하는 경우(a, b) -> a + b;로 표현 가능@FunctionalInterface을 사용해서 람다식을 위한 함수형 인터페이스를 지정한다. 메서드가 두개 이상 되면 컴파일 오류 발생.람다는 익명클래스처럼 Ex02_Lambda$1.class 클래스가 만들어지지 않는다.
@FunctionalInterface // 람다 표현식이 불가능하면 에러 발생
interface User3 {
void disp(int a);
}
void accept()T get()R apply(T t)T apply()boolean test package ch17.unit01;
import java.util.function.*;
public class Ex07 {
public static void main(String[] args) {
// 표준 API로 제공하는 함수적 인터페이스
// 매개변수가 있고, 리턴 값이 없는 추상 메서드
Consumer<Long> c = t -> System.out.println(t);
c.accept(100L);
// 매개변수가 없고, 리턴값이 존재하는 추상 메서드
IntSupplier i = () -> (int) (Math.random() * 10) + 1;
System.out.println(i.getAsInt());
Supplier<Integer> i1 = () -> (int) (Math.random() * 10) + 1;
System.out.println(i1.get());
// 매개변수가 두개인 경우
BiConsumer<String, String> b = (t, u) -> System.out.println(t + " : " + u);
b.accept("서울", "대한");
// Function<T, R> 매개변수(T)가 있고, 리턴값(R)이 있는 추상 메서드
Function<String, Integer> f = (s) -> Integer.parseInt(s);
System.out.println((int) f.apply("100"));
}
}
클래스명::메서드명
객체명::메서드명
package ch17.unit02;
import java.util.function.BiFunction;
public class MethodReference {
public static void main(String[] args) {
String s;
s = String.valueOf(100);
System.out.println(s + "n");
// 람다식
Test1 t1 = (num) -> String.valueOf(num);
s = t1.convert(150);
System.out.println(s + "\n");
// 메서드참조
Test1 t2 = String::valueOf;
s = t2.convert(150);
System.out.println(s + "\n");
}
}
interface Test1 {
String convert(Integer num);
}