[CHAPTER 3] - 람다 표현식 #24
Replies: 4 comments 2 replies
-
3.1 람다란 무엇인가?
// 기존 코드
Comparator<Apple> byWeight = new Comparator<Apple>{
public int compare(Apple a1, Apple a2) { <<<
return a1.getWeight().compareTo(a2.getWeight)); <<<
}
};
>>
// 변경코드
Coaparator<Apple> byWeight = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight)); |
Beta Was this translation helpful? Give feedback.
0 replies
-
3.2 어디에, 어떻게 람다를 사용할까?3.2.1 함수형 인터페이스
3.2.2 함수 디스크립터
|
Beta Was this translation helpful? Give feedback.
0 replies
-
3.3 람다 활용 : 실행 어라운드 패턴
3.3.1 1단계 : 동작 파라미터화를 기억하라
3.3.2 2단계 : 함수형 인터페이스를 이용해 동작 전달@FuncionalInterface
public interface BufferedReaderProcess {
String process(BufferedReader b) throws IOException;
}
public String processFile(BufferedReaderProcess p) throws IOException { ... } 3.3.3 3단계 : 동작 실행 public String processFile(BufferedReaderProcess p)) throws IOException {
try(BufferedReader br = new BufferedReader(new �FileReader("data.txt"))){
return p.process(br);
}
} 3.3.4 4단계 : 람다전달
|
Beta Was this translation helpful? Give feedback.
0 replies
-
3.4 함수형 인터페이스 사용
![]()
3.4.1 Predicate
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
public<T> List<T> filter(List<T> list, Predicate<T> p) {
List<T> results = new ArrayList<>();
for(T t : list) {
if(p.test(t)) {
results.add(t);
}
}
return results;
}
Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty();
List<String> nonEmpty = filter(listOfStrings, nonEmptyStringPredicate); 3.4.2 Consumer
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
public<T> void forEach(List<T> list, Consumer<T> c) {
for(T t : list) {
c.accept(t);
}
}
forEach(Arrays.asList(1,2,3,4,5), (Integer i) -> System.out.println(i)); 3.4.3 Function
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
public<T, R> List<R> map(List<T> list, Function<T, R> f) {
List<R> result = new ArrayList<>();
for(T t : list) {
result.add(f.apply(t));
}
return result;
}
//[7,2,6]
List<Integer> l = map(
Arrays.asList("lambdas", "in", "action"),
(String s) -> s.length()
); 기본형 특화
![]()
public interface IntPredicate {
boolean test(int t);
}
IntPredicate evenNumbers = (int i) -> i % 2 == 0;
evenNumbes.test(1000); //참(박싱x)
Predicate<Integer> oddNumbers = (integer i) -> i % 2 != 0;
oddNumbes.test(1000); //거짓(박싱) ![]() |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
3.0 이 장의 내용
람다
람다표현식
으로 가능람다표현식은 전체 책에서 광법위하게 사용하므로 완벽하게 이해해야 한다. ❗
Beta Was this translation helpful? Give feedback.
All reactions