1 /*
   2  * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
   3  *
   4  * Redistribution and use in source and binary forms, with or without
   5  * modification, are permitted provided that the following conditions
   6  * are met:
   7  *
   8  *   - Redistributions of source code must retain the above copyright
   9  *     notice, this list of conditions and the following disclaimer.
  10  *
  11  *   - Redistributions in binary form must reproduce the above copyright
  12  *     notice, this list of conditions and the following disclaimer in the
  13  *     documentation and/or other materials provided with the distribution.
  14  *
  15  *   - Neither the name of Oracle nor the names of its
  16  *     contributors may be used to endorse or promote products derived
  17  *     from this software without specific prior written permission.
  18  *
  19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  20  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30  */
  31 
  32 /*
  33  * This source code is provided to illustrate the usage of a given feature
  34  * or technique and has been deliberately simplified. Additional steps
  35  * required for a production-quality application, such as security checks,
  36  * input validation and proper error handling, might not be present in
  37  * this sample code.
  38  */
  39 package stream;
  40 
  41 import stream.data.Customer;
  42 import stream.data.Product;
  43 import stream.data.Order;
  44 import java.util.ArrayList;
  45 import java.util.Comparator;
  46 import static java.util.Comparator.*;
  47 import java.util.List;
  48 import java.util.Map;
  49 import java.util.Optional;
  50 import java.util.function.BiConsumer;
  51 import java.util.function.Function;
  52 import java.util.stream.Collector;
  53 import java.util.stream.Collectors;
  54 import static java.util.stream.Collectors.*;
  55 import java.util.stream.Stream;
  56 
  57 /**
  58  * This class demos shows usage of group Collector working with collect method.
  59  *
  60  * @author tyan
  61  */
  62 public class Grouping extends DemoHelper {
  63 
  64     /**
  65      * Group products by T
  66      *
  67      * @param byXXX a function which convert Product to T
  68      * @return a map between T object to a product list, any product in this
  69      * list using byXXX conversion is same to map's key
  70      */
  71 
  72     public static <T> Map<T, List<Product>> groupProduct(
  73             Function<Product, T> byXXX) {
  74         return products.stream().
  75                 //grouping product by given function
  76                 collect(groupingBy(byXXX));
  77     }
  78 
  79     /**
  80      * Group orders by customer with using Collectors.groupingBy(Function,
  81      * Collector)
  82      *
  83      * @return map customer to its order list
  84      */
  85     public static Map<String, List<Order>> groupOrdersByCustomer() {
  86         //a collector that generate a order list from a customer
  87         Collector<Customer, List<Order>, List<Order>> collectOrder = Collector.
  88                 of(ArrayList<Order>::new,
  89                         (orders, customer) -> {
  90                             orders.addAll(customer.getOrders());
  91                         },
  92                         (left, right) -> {
  93                             left.addAll(right);
  94                             return left;
  95                         });
  96         return customers.stream().
  97                 //convert customers to a Map which key is it name, value is its
  98                 //orders
  99                 collect(groupingBy(Customer::getCompanyName,
 100                                 collectOrder));
 101     }
 102 
 103     /**
 104      * Group products by categories, only select max/min value of product
 105      * ordered by compFunc
 106      *
 107      * @param maxBy true select max value product false select min value product
 108      * @param groupFunc function provides how to group product
 109      * @param compFunc function provides how to sort product
 110      * @return a map between a instance of S to instance of T
 111      */
 112     public static <S, T extends Comparable<T>> Map<S, Optional<Product>>
 113             productMaxByTGroupByS(boolean maxBy, Function<Product, S> groupFunc,
 114                     Function<Product, T> compFunc) {
 115         //Comparator of Product which will compare on T by given function
 116         Comparator<Product> comp = comparing(compFunc);
 117         //A collector that collet maximal or minimal element according to a
 118         //given maxBy and Comparator
 119         Collector<Product, ?, Optional<Product>> collector
 120                 = maxBy ? maxBy(comp) : minBy(comp);
 121         return products.stream().
 122                 //collect products into a Map, which key is S by function of
 123                 //groupFunc, value is max or min by given max and function of
 124                 //compFunc
 125                 collect(Collectors.groupingBy(groupFunc, collector));
 126     }
 127 
 128     /**
 129      * Group products by R, this is demo for grouping by different element one
 130      * by one.
 131      *
 132      * @param func1 function that convert Product to R
 133      * @param func2 function that convert Product to T
 134      * @return a map which groups products to R then T
 135      */
 136     public static <R, T> Map<R, Map<T, List<Order>>> ordersByRThenT(
 137             Function<Order, R> func1, Function<Order, T> func2) {
 138         return customers.stream().collect(
 139                 streaming(customer -> customer.getOrders().stream(),
 140                         groupingBy(func1, groupingBy(func2))));
 141     }
 142 
 143     /**
 144      * A downstream collector that streams elements to a further downstream
 145      * collector.
 146      *
 147      * @param <T> the type of the input elements
 148      * @param <U> the supplier type of the downstream collector
 149      * @param <A> the intermediate accumulation type of the downstream collector
 150      * @param <R> the result type of the downstream reduction
 151      * @param mapper the classifier function mapping input elements to object of
 152      * U
 153      * @param downstream a collector implementing the downstream reduction
 154      * @return a collector convert element to other object followed by an
 155      * downstream a collector which performs the action
 156      */
 157     public static <T, U, A, R>
 158             Collector<T, ?, R> streaming(Function<? super T, ? extends Stream<? extends U>> mapper,
 159                     Collector<? super U, A, R> downstream) {
 160         BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
 161         return Collector.of(downstream.supplier(),
 162                 (r, t) -> mapper.apply(t).sequential().forEach(
 163                         u -> downstreamAccumulator.accept(r, u)),
 164                 downstream.combiner(),
 165                 downstream.finisher(),
 166                 downstream.characteristics().stream().toArray(
 167                         Collector.Characteristics[]::new));
 168     }
 169 
 170 }