2020/12/09 - [JAVA] - Stream-1

이전글:

 

Stream-1

자료의 대상과 관계없이 동일한 연산을 수행할 수 있는 기능 배열, 컬렉션에 동일한 연산이 수행되어 일관성 있는 처리 가능 한번 생성하고 사용한 스트림은 재사용할 수 없음 스트림 연산은 기

kwaksh2319.tistory.com

이번엔 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

 

BinaryOperator (Java Platform SE 8 )

Represents an operation upon two operands of the same type, producing a result of the same type as the operands. This is a specialization of BiFunction for the case where the operands and the result are all of the same type. This is a functional interface

docs.oracle.com

docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html#apply-T-U-

 apply :

 

BiFunction (Java Platform SE 8 )

 

docs.oracle.com

 

여기서 우리는BinaryOperator인터페이스로부터 apply메서드를 오버라이딩을 받습니다.

 

java.util 패키지의 Optional, OptionalDouble, OptionalInt, OptionalLong 클래스

docs.oracle.com/javase/8/docs/api/java/util/Optional.html

 

Optional (Java Platform SE 8 )

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orEl

docs.oracle.com

docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

 

java.util.stream (Java Platform SE 8 )

Interface Summary  Interface Description BaseStream > Base interface for streams, which are sequences of elements supporting sequential and parallel aggregate operations. Collector A mutable reduction operation that accumulates input elements into a mutab

docs.oracle.com

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

+ Recent posts