가자미의 개발이야기
자바 다양한 람다식 본문
-함수형 인터페이스?(Functional Interface?)
--추상메소드가 하나 있는 인터페이스
--람다식을 위한 전제
-매개변수가 있고 반환하지 않는 람다식
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
interface Printable{
void print(String s);
}
public class Ramda {
public static void main(String[] args) {
Printable p;
//줄임없는 표현
p=(String s)->{System.out.println(s);};
//메소드 코드가 한줄 일때만 중괄호 생략
p=(String s)->System.out.println(s);
//매개변수 형 생략
p=(s)->System.out.println(s);
//매개변수 소괄호 생략
p=s->System.out.println(s);
}
}
|
cs |
-매개변수가 둘인 람다식
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
interface Calculate{
void cal(int a, int b);
}
public class Ramda {
public static void main(String[] args) {
Calculate c;
//뺄셈실행
c=(a,b)->{System.out.println(a-b);};
c.cal(4,3);
//덧셈실행
c=(a,b)->System.out.println(a+b);
c.cal(4, 3);
}
}
|
c |
-매개변수가 있고 반환하는 람다식
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
interface Calculate{
int cal(int a, int b);
}
public class Ramda {
public static void main(String[] args) {
Calculate c;
//return문 사용할 경우
c=(a,b)->{return a+b;};//return문 사용시 중괄호 생략 안됨
System.out.println(c.cal(4,3));
c=(a,b)->a+b;//연산결과가 남으면, 별도로 명시하지 않아도 반환
System.out.println(c.cal(4, 3));
}
}
|
cs |
-매개변수가 없는 람다식
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import java.util.Random;
interface Generator{
int rand();
}
public class Ramda {
public static void main(String[] args) {
Generator gen=()->{
Random rand = new Random();
return rand.nextInt();
};
System.out.println(gen.rand());
}
}
|
cs |
'Java > 자바 기본 문법' 카테고리의 다른 글
자바 람다 정의되어 있는 함수형 인터페이스 (0) | 2021.02.04 |
---|---|
자바 람다의 어노테이션과 제네릭 (0) | 2021.02.04 |
자바 람다의 기초 (0) | 2021.02.04 |
자바 네스티드 클래스 (0) | 2021.02.04 |
자바 매개변수의 가변 인자 선언 & 어노테이션 (0) | 2021.02.03 |