Java
스트림/람다식 사용하여 가장 긴 문자열 추출하기
LearnerKSH
2021. 10. 18. 18:01
728x90
반응형
Todo. 가장 긴 문자열 추출하기
- 1. Stream 사용
public class ReduceTest {
public static void main(String[] args) {
String values[] = {"Hello", "World", "!"};
/* 가장 긴 length 문자열 추출 */
String reduce = Arrays.stream(values).reduce("", (s1, s2) -> {
if (s1.getBytes().length >= s2.getBytes().length) {
return s1;
} else {
return s2;
}
});
}
}
- 2. Lamda 사용
class CompareString implements BinaryOperator<String> {
@Override
public String apply(String s1, String s2) {
if (s1.getBytes().length >= s2.getBytes().length) {
return s1;
} else {
return s2;
}
}
}
호출코드
public class ReduceTest {
public static void main(String[] args) {
String values[] = {"Hello", "World", "!"};
/* lamda */
String reduce2 = Arrays.stream(values).reduce(new CompareString()).get();
System.out.println(reduce2);
}
}
내부 코드 분석하기
- reduce 메서드
Optional<T> reduce(BinaryOperator<T> accumulator);
- BinaryOperator 인터페이스
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
...
}
- BiFunction 인터페이스
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
...
}
BiFunction 인터페이스는 함수형 인터페이스이다. apply 메서드를 우린 CompareString 구현 클래스에서 오버라이드로 재정의를 했고, main 메서드에서 호출한 아래의 코드는 람다식이 사용되어 apply 내부 코드가 실행되어 결과가 출력된다.
String reduce2 = Arrays.stream(values).reduce(new CompareString()).get();
반응형