Java

[Java] 스트림으로 데이터 수집 - 분할

snail voyager 2023. 8. 9. 00:00
728x90
반응형

분할

  • Predicate를 분류 함수로 사용하는 특수한 그룹화 기능
  • 분할 함수는 boolean을 반환하므로 Map의 키 형식은 Boolean
Map<Boolean, List<Dish>> partitionedMenu = menu.stream().collect(partitionBy(Dish::isVegetarian);
//{false=[pork, beef, chicken, prawns, salmon], true=[french fries, rice, season fruit, pizza]}

List<Dish> vegetarianDishes = partitionedMenu.get(true);	//채식 요리
List<Dish> vegetarianDishes = menu.stream().filter(Dish::isVegetarian).collect(toList());	//동일

분할의 장점

  • 분할 함수가 반환하는 참, 거짓 두가지 요소의 스트림 리스트를 모두 유지함
  • 컬렉터를 두번째 인수로 전달 가능
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, season fruit]}}

Map<Boolean, Dish> mostCaloricPartitionByVegetarian = menu.stream().collect(
	partitioningBy(Dish::isVegetarian,
    	collectingAndThen(maxBy(comparingInt(Dish::getCalories)),	//각 그룹에서 가장 칼로리가 높은 요리
        		Optional::get)));
//{false=pork, true=pizza}

 

728x90
반응형