본문
170419(수) - Lambda Expressions
Programming/Java 8 2017. 4. 19. 18:15
Lambda Expressions
- 기존
interface CheckPerson { boolean test(Person p); }
printPersons( roster, new CheckPerson() { public boolean test(Person p) { return p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25; } } );
- 람다 사용
printPersons( roster, (Person p) -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25 );
ㆍ매개변수가 하나뿐이라면 괄호 생략 가능
printPersonsWithPredicate( roster, p -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25 );
ㆍ규약서 정의
() -> {} // No parameters; result is void
() -> 42 // No parameters, expression body
() -> null // No parameters, expression body
() -> { return 42; } // No parameters, block body with return
() -> { System.gc(); } // No parameters, void block body
() -> {
if (true) return 12;
else {
int result = 15;
for (int i = 1; i < 10; i++)
result *= i;
return result;
}
} // Complex block body with returns
(int x) -> x+1 // Single declared-type parameter
(int x) -> { return x+1; } // Single declared-type parameter
(x) -> x+1 // Single inferred-type parameter
x -> x+1 // Parens optional for single inferred-type case
(String s) -> s.length() // Single declared-type parameter
(Thread t) -> { t.start(); } // Single declared-type parameter
s -> s.length() // Single inferred-type parameter
t -> { t.start(); } // Single inferred-type parameter
(int x, int y) -> x+y // Multiple declared-type parameters
(x,y) -> x+y // Multiple inferred-type parameters
(final int x) -> x+1 // Modified declared-type parameter
(x, final y) -> x+y // Illegal: can't modify inferred-type parameters
(x, int y) -> x+y // Illegal: can't mix inferred and declared types
'Programming > Java 8' 카테고리의 다른 글
170420(목) - Streams <Terminal Operations> (0) | 2017.04.20 |
---|---|
170420(목) - Streams <Intermediate Operations> (0) | 2017.04.20 |
170420(목) - Streams <Laziness and Performance Optimization> (0) | 2017.04.20 |
170420(목) - Streams <Understanding Java 8 Streams API (0) | 2017.04.20 |
170419(수) - Default Methods (0) | 2017.04.19 |
댓글