[Java8] 스트림으로 데이터 수집

스트림으로 데이터 수집

목차

컬렉터란 무엇인가?

고급 리듀싱 기능을 수행하는 컬렉터

리듀싱 연산

미리 정의된 컬렉터

리듀싱과 요약

스트림값에서 최댓값과 최솟값 검색

Comparator<Dish> dishCaloriesComparator =
      Comparator.comparinglnt(Dish::getCalories);
Optional<Dish> mostCalorieDish =
                menu.stream()
                .collect(maxBy(dishCaloriesComparator));

요약 연산

int totalCalories = menu.stream().collect(summingInt(Dish::getCalories));
IntSummaryStatistics menuStatistics =
menu.stream().collect(summarizinglnt(Dish::getCalories));
// IntSummaryStatistics { count=9, sum=4388, min=128,average=477.777778, max=888 }

문자열 연결

String shortMenu = menu.stream().map(Dish::getName).collect(joining(", "));
// pork, beef, chicken, french fries, rice, season fruit, pizza, prawns, salmon

범용 리듀싱 요약 연산

그룹화

Map<Dish.Type, List<Dish>> dishesByType = menu.stream().collect(groupingBy(Dish::getType));
// {FISH=[prawns, salmon], OTHER=[french fries, rice, season fruit, pizza], MEAT=[pork, beef, chicken]}

다수준 그룹화

Map<Dish.Type, Map<CaloricLevel , List<Dish>>> dishesByTypeCaloricLevel =
  menu.stream().collect(
    groupingBy(Dish::getType,
      groupingBy(dish -> {
        if (dish.getCalories() <= 400) {
          return C때ricLevel.DIET;
        } else if (dish. getCalories () <= 700) {
          return CaloricLevel.NORMAL;
        } else {  
          return CaloricLevel.FAT;
        }
      })
  )
);
/*
{MEAT={DIET=[chicken], NORMAL=[beef], FAT=[pork]},
FISH={DIET=[prawns], NORMAL=[salmon]},
OTHER={DIET=[rice, seasonal fruit], NORMAL=[french fries, pizza]}}
*/

서브그룹으로 데이터 수집

Map<Dish.Type, Long> typesCount = menu.stream( ).collect(groupingBy(Dish::getType, counting()));
// {MEAT=3, FISH=2 , OTHER=4}

분할

Map<Boolean, List<Dish>> partitionedMenu =
                menu.stream().collect(partitioningBy(Dish::isVegetarian));

분할의 장점

Map<Boolean, Map<Dish.Type , List<Dish>>> vegetarianDishesByType =
menu.stream().collect(
                    partitioningBy(Dish::isVegetarian,
                    groupingBy(Dish::getType)));
// {false={FISH=[prawns, salmon], MEAT=[pork, beef, chicken]},true={OTHER=[french fries, rice, seasonfruit , pizza]}}

Collections에서 제공하는 정적 팩토리 메서드로 만들 수 있는 모든 컬렉터

Collections-1

Collections-2

요약