본문 바로가기

DEVELOPER/Java

reduce( ) 연산

반응형

reduce( ) 연산


  • 정의된 연산이 아닌 프로그래머가 직접 구현한 연산을 적용
T reduce( T identify, BinaryOperator<T> accumulator )

*T idetify는 기본값 
*BinaryOperator<T> accumulator 는 BinaryOperator인터페이스를 구현한 부분
                                                 -> 람다식으로 직접 쓸 수도 있음
  • 최종 연산으로 스트림의 요소를 소모하며 연산을 수행
  • reduce( ) 메서드의 두 번째 요소로 전달되는 람다식에 따라 다양한 기능을 수행 할 수 있음
  • 람다식을 직접 구현하거나 람다식이 긴 경우 BinaryOperator를 구현한 클래스를 사용

 

reduce( ) 연산 구현 예


◎ 배열의 모든 요소의 합을 구하는 reduce( ) 연산 구현


Arrays.stream(arr).reduce(0, (a,b) -> a+b));

 

 

◎ 배열에 여러 문자열이 있을 때 길이가 가장 긴 문자열 찾기


① 람다식 구현

public class ReduceTest {

	public static void main(String[] args) {
    	
        String[] greetings = {"안녕하세요~~~", "hello", "Good morning", "반갑습니다^^"};
        
        System.out.println(Arrays.stream(greetings).reduce(" ", (s1, s2)-> {
        						if (s1.getByts().length >= s2.getBytes().length)
                                	return s1;
                                else return s2;}
        ));
   
}

 

② BinaryOperator 인터페이스를 직접 구현한 클래스 

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[] greetrings = {"안녕하세요~~", "hello", "Good morning", "반갑습니다~~^^"};
        
       	 	//BinaryOperator를 구현한 클래스 이용
  		String str = Arrays.stream(greetings).reduce(new CompareString()).get();
        	System.out.println(str);
	}
}

 

반응형

'DEVELOPER > Java' 카테고리의 다른 글

예외 처리 미루기  (0) 2021.05.08
Java의 예외 처리하기 - Exception  (0) 2021.05.07
스트림(Stream)  (0) 2021.05.06
람다식(Lambda expression)  (0) 2021.05.05
내부 클래스(inner class)  (0) 2021.05.04