Collector 인터페이스 구현은 스트림의 요소를 어떤 식으로 도출할지 결정.

예를 들면 Collector 인터페이스의 구현으로 toLost는 각 요소들을 리스트로 만들어줍니다.

미리 정의된 컬렉터의 기능과 커스텀해서 만드는 기능에 대해서 정리해보려고 합니다.

크게 Collector 는 요약, 그룹화, 분할로 나눌 수 있습니다.

이번 글에서는 요약에 대해서 정리해보겠습니다.

 

먼저 예제에서 사용할 Game 리스트를 생성해보겠습니다.

List<Game> games = Arrays.asList(
		new Game("CALL 1", 20000)
		, new Game("DIA 3", 30000)
		, new Game("DIA 2", 40000)
		, new Game("DIA 1", 50000)
);

 

counting

아래 예제는 리스트 모든 요소들을 카운팅 하는 예제입니다.

long countGames = games.stream().collect(Collectors.counting());

다음과 같이 Colletors 클래스를 import 하면 아래와 같이 더욱더 간단하게 작성이 가능합니다.

이제부터 살펴볼 예제는 Collectors 클래스를 import 한 상태로 진행하겠습니다.

import static java.util.stream.Collectors.*;
long countGames = games.stream().collect(counting());

 

maxBy와 minBy

최대값 최솟값을 구하는 예제를 살펴보겠습니다.

Comparator<Game> gamesComparator = Comparator.comparingInt(Game::getPrice);
Optional<Game> maxPriceGame = games.stream()
				.collect(maxBy(gamesComparator)); 
                
Optional<Game> minPriceGame = games.stream()
				.collect(minBy(gamesComparator)); 
		
System.out.println(maxPriceGame.get().getPrice());
System.out.println(minPriceGame.get().getPrice());

결과값

50000
20000

 

summingInt

객체를 int로 맵핑하는 함수를 인수로 받아 객체를 int 로 맵핑하여 컬렉터를 반환하는 메서드.

int totalPriceGame = games.stream().collect(summingInt(Game::getPrice));
System.out.println(totalPriceGame);

결과값

140000

 

averagingInt

평균값을 계산하는 메서드.

double avgPriceGame = games.stream().collect(averagingInt(Game::getPrice));
System.out.println(avgPriceGame);

결과값

35000.0

 

summarizingInt

요소를 카운팅 한 숫자, 합계, 평균, 최댓값, 최솟값을 연산하는 메서드.

IntSummaryStatistics priceGameStat = games.stream().collect(summarizingInt(Game::getPrice));
System.out.println(priceGameStat);

결과값

IntSummaryStatistics{count=4, sum=140000, min=20000, average=35000.000000, max=50000}

 

joining

각 객체의 toString 메서드를 호출해서 추출한 문자열들을 하나의 문자열로 합쳐서 반환.

String gameName = games.stream()
		.map(game -> game.getName().split(" ")[0]) // 문자열을 쪼개서 첫번째 문자열을 생성.
		.collect(joining(",")); // 각 첫번째 문자열을 합친다. 구분자는 ","
        
System.out.println(gameName);

결과값

CALL,DIA,DIA,DIA

 

reducing

리듀싱 구현 기능을 제공하는 메서드.

아래는 price 합을 구하는 예제를 reducing 메서드를 이용해 구현.

int totalPriceGame = games.stream().collect(reducing(0, Game::getPrice, (i, j) -> i + j));
System.out.println(totalPriceGame);

첫 번째 인수는 시작 값 또는 인수가 없을 때 반환 값.

두 번째 인수는 price 반환 함수

세 번째 인수는 두 개의 항목을 하나로 합하는 BinaryOperator 이다.

 

결과값

140000

 

다음은 price 최대 값을 구하는 예제.

Optional<Game> maxGamePrice = games.stream().collect(Collectors.reducing((i, j) -> i.getPrice() > j.getPrice() ? i : j));
System.out.println(maxGamePrice.get().getPrice());

결과값

50000

 

 

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

Collector 분할  (0) 2022.11.08
Collector 그룹화  (0) 2022.11.01
스트림 생성  (0) 2022.10.27
기본형 특화 스트림  (0) 2022.10.27
리듀싱  (0) 2022.10.26

+ Recent posts