Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

Formoat's Open Blog

스트림 최종 처리 본문

Java/Java Basic

스트림 최종 처리

snd-snd 2019. 9. 4. 00:27
Function Return Type Method Interface Remarks
매칭 boolean allMatch( ... ) Stream, IntStream, LongStream, DoubleStream 모든 요소가 조건에 만족
anyMatch( ... ) 단 하나라도 조건에 만족
noneMatch( ... ) 모든 요소가 조건에 만족X
집계 long count() 요소 개수 카운팅
OptionalXXX findFirst() 첫번째 요소
Optional<T> max( ... ) 최대값
Optional<T> min( ... ) 최소값
... reduce( ... ) 커스텀 집계 메소드
OptionalDouble average( ... ) IntStream, LongStream, DoubleStream 평균
int, long, double sum() 합계
루핑   forEach( ... ) Stream, IntStream, LongStream, DoubleStream 요소를 하나씩 소비
수집   collect( ... )  

<표> 최종 처리 메소드의 종류

 

 

 

# 매칭

요소들이 특정 조건을 만족하는지 조사하는 것

(1) allMatch(Predicate<T>) : 스트림 내 요소가 Predicate 조건에 모두 만족한다면 true를 반환

(2) anyMatch(Predicate<T>) : 스트림 내 요소 중 단 하나라도 Predicate 조건에 만족한다면 true를 반환

(3) noneMatch(Predicate<T>) : 스트림 내 요소가 Predicate 조건에 모두 만족하지 않는다면 true를 반환

 

 

MatchExample.java

public class MatchExample {

	public static void main(String[] args) {
		
		int arr[] = {1,2,3,4,5};
		
		boolean result;
		
		result = Arrays.stream(arr).allMatch(a -> a < 10);
		System.out.println("요소 모두 10보다 작은가? "+result);
		
		result = Arrays.stream(arr).anyMatch(a -> a == 5);
		System.out.println("요소중 하나라도 5가 있는가? "+result);
		
		result = Arrays.stream(arr).noneMatch(a -> a > 10);
		System.out.println("요소 모두 10보다 작은가? "+result);				
	}
}

 

// 실행결과 //
----------------------------------------------------
요소 모두 10보다 작은가? true
요소중 하나라도 5가 있는가? true
요소 모두 10보다 작은가? true

 

 

 

# 집계

카운팅, 합계, 평균, 최소값, 최대값 등 하나의 값으로 산출하는 것으로 대량의 데이터(요소)를 가공해 축소하는 리덕션이라고 할 수 있다.

(1) count() : 요소의 총 개수를 카운팅

(2) findfirst() : 첫번째 요소를 반환

(3) max() : 요소 중 최대 값

(4) min() : 요소 중 최소값

(5) average() : 요소의 평균

(6) sum() : 요소의 합계

 

 

Aggregate.java

public class Aggregate {

	public static void main(String[] args) {
		
		int arr[] = {1,2,3,4,5};
		
		long count = Arrays.stream(arr)
				.count(); // 총 개수
		
		int first = Arrays.stream(arr)
				.findFirst() // 첫번째 요소
				.getAsInt();
		
		int max = Arrays.stream(arr)
			.max() // 최대값
			.getAsInt();
		
		int min = Arrays.stream(arr)
			.min() // 최소값
			.getAsInt();
		
		double avg = Arrays.stream(arr)
			.average() // 평균
			.getAsDouble();
		
		int sum = Arrays.stream(arr)
			.sum(); // 합계
		
		System.out.println("요소의 총 개수: " + count);
		System.out.println("첫번째 요소: " + first);
		System.out.println("최대값: " + max);
		System.out.println("최소값: " + min);
		System.out.println("평균: " + avg);
		System.out.println("합계: " + sum);
	}
}

 

// 실행결과 //
----------------------------------------------------
요소의 총 개수: 5
첫번째 요소: 1
최대값: 5
최소값: 1
평균: 3.0
합계: 15

 

 

(7) reduce : 사용자 정의 집계 함수로 다양한 결과를 만들 수 있다.

 

Interface Return Type Method
Steram Optionnal<T> reduce(BinaryOperator<T> accumulator)
T reduce(T identity, BinaryOperator<T> accumulator)
IntSteram OptionnalInt reduce(IntBinaryOperator op)
int reduce(int identity, IntBinaryOperator op)
LongSteram OptionnalLong reduce(LongBinaryOperator op)
long reduce(long identity, LongBinaryOperator op)
DoubleSteram OptionnalDouble reduce(DoubleBinaryOperator op)
double reduce(double identity, DoubleBinaryOperator op)

<표> reduce 메소드의 종류

 

 

reduce 메소드는 각 스트림별로 2개씩 메소드가 오버로딩 되어있다.

첫 번째 메소드는 두개의 매개값을 받아 결과를 반환하는 BinaryOperator 함수적 인터페이스를 사용한다.

다만 스트림에 요소가 없을 경우 매개값을 받을 수 없기 때문에 NoSuchElementException이 발생 하게 되는데,

이를 방지하기 위해 두번째 메소드를 사용하게 된다. 두 번째 메소드의 identity는 기본값으로서

만약 스트림에 요소가 없어 연산을 하지 못할 경우 지정된 기본값을 결과로서 반환하게 된다.

 

 

ReduceExample.java

public class ReduceExample {

	public static void main(String[] args) {
		
		int arr[] = {10,20,30,40,50};
		int result;
		
		try {
		result = Arrays.stream(arr)
			.filter(a -> a > 100)
			.reduce((a,b)->a+b) // reduce(IntBinaryOperator op) 사용
			.getAsInt();
			System.out.println(result);
		} catch (NoSuchElementException e) {
			System.out.println("NoSuchElementException 발생");
		}
		
		result = Arrays.stream(arr)
			.filter(a -> a > 100)
			.reduce(100, (a,b)->a+b); // reduce(int identity, IntBinaryOperator op) 사용
			System.out.println(result);
	}
}

// 실행결과 //
----------------------------------------------------
NoSuchElementException 발생
100

 

 

 

# 수집

 

미작성

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

Java API Document  (0) 2019.09.04
제네릭 (Generic)  (0) 2019.09.04
스트림 중간 처리  (0) 2019.09.04
스트림 (Stream)  (0) 2019.09.04
컬렉션 - Stack, Queue  (0) 2019.09.04
Comments