티스토리에 저장했던 글을 옮겼습니다.
https://mrcocoball.tistory.com/90
(int x, int y) -> {return x+y;}
str->{System.out.println(str);}
str-> System.out.println(str);
(x, y) -> x+y;
str -> str.length;
public interface Add { // 함수를 구현하기 위한 인터페이스
public int add(int x, int y); // 람다식으로 만들 추상 메소드
}
public class AddTest {
public static void main(String[] args) {
Add addL = (x, y) -> {return x+y;}; // 인터페이스 Add의 add 메소드를 람다식으로
System.out.println(addL.add(2,3));
}
}
@FunctionalInterface
애노테이션 추가 (함수형 인터페이스라는 의미)@FunctionalInterface
public interface Max {
int getMax(int num1, int num2);
}
public class MaxTest {
public static void main(String[] args) {
Max max = (x,y) -> x > y? x : y;
System.out.println(max.getMax(20,30));
}
}
@FunctionalInterface
public interface StringConcat {
public void makeString(String s1, String s2);
}
public class StringConcatImpl implements StringConcat{
@Override
public void makeString(String s1, String s2) {
System.out.println(s1 + s2);
}
}
public class StringConcatTest {
public static void main(String[] args) {
String s1 = "이엣";
String s2 = "타이가";
// O.O.P로 구현
/* StringConcatImpl strImp = new StringConcatImpl();
strImp.makeString(s1, s2); */
// 람다식으로 구현
StringConcat concat = (s, v) -> System.out.println(s + v); // 람다식 자체가 익명 객체를 생성함
concat.makeString(s1, s2);
}
}
public interface PrintString {
void showString(String str);
}
public class TestLambda {
public static void main(String[] args) {
PrintString lambdaStr = s->System.out.println(s); //람다식을 변수에 대입
lambdaStr.showString("hello lambda_1");
showMyString(lambdaStr); //메서드 매개변수로 전달
PrintString reStr = returnString();
reStr.showString("hello ");
}
public static void showMyString(PrintString p) {
p.showString("hello lambda_2");
}
public static PrintString returnString() { //반환 값으로 사용
return s->System.out.println(s + "world");
}
}