2020/12/09 - [JAVA] - Stream-1
이전글:
이번엔 custom 할수 있는 stream 메서드를 확인해보겠습니다.
reduce();
먼저 코드로 확인해보겠습니다.
public class Main {
public static void main(String [] args) {
String[] greetings= {"안녕하세요.~~~","Hello","Good Morning","반갑습니다."};
System.out.println(Arrays.stream(greetings).reduce("", (s1,s2)->
{
if(s1.getBytes().length>=s2.getBytes().length)
return s1;
else return s2;
}//lamda
)//reduce
);//syso
}
}
딱봐도 음 너무 보기 힘들다는 느낌이 있습니다. 그렇다면 System.out.println 안을 확인해보겠습니다.
Arrays.stream(greetings).reduce("", (s1,s2)->
{
if(s1.getBytes().length>=s2.getBytes().length)
return s1;
else return s2;
}//lamda
)//reduce
stream은 들어갈 배열이고 reduce 메서드를 확인해보겠습니다.
람다식과 동일한 방식으로
(매게변수)->{조건 결과}
"", (s1,s2)->
{
if(s1.getBytes().length>=s2.getBytes().length)
return s1;
else return s2;
}//lamda
정말 보기 힘드니까 클래스화해서 확인해보겠습니다.
조건들을 전부 클래스로 보내줍니다.
BinaryOperator인터페이스:
docs.oracle.com/javase/8/docs/api/java/util/function/BinaryOperator.html
docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html#apply-T-U-
apply :
여기서 우리는BinaryOperator인터페이스로부터 apply메서드를 오버라이딩을 받습니다.
java.util 패키지의 Optional, OptionalDouble, OptionalInt, OptionalLong 클래스
docs.oracle.com/javase/8/docs/api/java/util/Optional.html
docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
stream도 java.util 패키지에 존재합니다. 그래서 get 함수를 사용하여Optional 클래스를 통해서 .get() value를 리턴할수 있습니다.
class CompareStrings implements BinaryOperator<String>{
@Override
public String apply(String s1, String s2) {
// TODO Auto-generated method stub
if(s1.getBytes().length>=s2.getBytes().length)
return s1;
else return s2;
}
}
그렇다면 현재 조건들을 apply(매개변수) 함수에 입력한 후 조건들을 넣어줍니다.
아래 코드로 출력해줍니다.
System.out.println(Arrays.stream(greetings).reduce(new CompareStrings()).get());
이전보다 훨씬 간결한 코드가 되었습니다. 한번 쪼개서 보겠습니다.
Arrays.stream(greetings).reduce(new CompareStrings()).get()
reduce()
reduce(new CompareStrings()).get()
CompareStrings 동적할당 인스턴스화
new CompareStrings()
Apply 함수 get()해옴
.get()
출력:
'프로그래밍언어 > JAVA' 카테고리의 다른 글
<JAVA> 예외처리-2 (0) | 2020.12.11 |
---|---|
<JAVA>예외처리-1 (0) | 2020.12.11 |
<JAVA>Stream-1 (0) | 2020.12.09 |
<JAVA>람다식 (0) | 2020.12.09 |
<JAVA> 익명 내부 클래스 (0) | 2020.12.09 |