Example usage for java.util.stream Collectors groupingBy

List of usage examples for java.util.stream Collectors groupingBy

Introduction

In this page you can find the example usage for java.util.stream Collectors groupingBy.

Prototype

public static <T, K, A, D> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
        Collector<? super T, A, D> downstream) 

Source Link

Document

Returns a Collector implementing a cascaded "group by" operation on input elements of type T , grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector .

Usage

From source file:Main.java

public static void main(String[] args) {
    Map<Employee.Gender, DoubleSummaryStatistics> incomeStatsByGender = Employee.persons().stream().collect(
            Collectors.groupingBy(Employee::getGender, Collectors.summarizingDouble(Employee::getIncome)));

    System.out.println(incomeStatsByGender);
}

From source file:Main.java

public static void main(String[] args) {
    Map<Month, String> dobCalendar = Employee.persons().stream()
            .collect(Collectors.collectingAndThen(Collectors.groupingBy(p -> p.getDob().getMonth(),
                    Collectors.mapping(Employee::getName, Collectors.joining(" "))), result -> {
                        for (Month m : Month.values()) {
                            result.putIfAbsent(m, "None");
                        }//from w w w . j  av a  2s. com
                        return Collections.unmodifiableMap(new TreeMap<>(result));
                    }));

    dobCalendar.entrySet().forEach(System.out::println);
}

From source file:Main.java

public static void main(String[] args) {
    List<Person> roster = createRoster();

    System.out.println("Total age by gender:");
    Map<Person.Sex, Integer> totalAgeByGender = roster.stream().collect(
            Collectors.groupingBy(Person::getGender, Collectors.reducing(0, Person::getAge, Integer::sum)));

    List<Map.Entry<Person.Sex, Integer>> totalAgeByGenderList = new ArrayList<>(totalAgeByGender.entrySet());

    totalAgeByGenderList.stream()/*  w w  w  . ja  v a 2s .c  om*/
            .forEach(e -> System.out.println("Gender: " + e.getKey() + ", Total Age: " + e.getValue()));

}

From source file:Main.java

public static void main(String[] args) {
    List<Person> roster = createRoster();

    System.out.println("Names by gender:");
    Map<Person.Sex, List<String>> namesByGender = roster.stream().collect(
            Collectors.groupingBy(Person::getGender, Collectors.mapping(Person::getName, Collectors.toList())));

    List<Map.Entry<Person.Sex, List<String>>> namesByGenderList = new ArrayList<>(namesByGender.entrySet());

    namesByGenderList.stream().forEach(e -> {
        System.out.println("Gender: " + e.getKey());
        e.getValue().stream().forEach(f -> System.out.println(f));
    });/*ww  w .  ja v a  2s.  com*/

}

From source file:Main.java

/**
 * Returns a collector that computes the distribution of the provided elements. This effectively counts how many
 * times an item has appeared in a stream.
 *
 * @param <T>/*from   w  w  w .  jav a  2  s  .c om*/
 *            the counted type
 * @return the distribution collector
 */
public static <T> Collector<T, ?, Map<T, Long>> distribution() {
    return Collectors.groupingBy(Function.identity(), Collectors.counting());
}

From source file:com.firewallid.util.FIUtils.java

public static <L> Map<L, Long> reduceListToMap(List<L> l) {
    Map<L, Long> map = l.parallelStream()
            .collect(Collectors.groupingBy(object -> object, Collectors.counting()));

    return map;//from  w w w.  java  2 s.  c o m
}

From source file:com.firewallid.util.FIUtils.java

public static <U, V extends Number> List<Tuple2<U, Double>> sumList(List<Tuple2<U, V>> l1,
        List<Tuple2<U, V>> l2) {
    l1.addAll(l2);/*ww w.  j  a  va 2s .  c o m*/
    List<Tuple2<U, Double>> sum = l1.parallelStream()
            .collect(Collectors
                    .groupingBy(data -> data._1(), Collectors.mapping(data -> data._2(), Collectors.toList())))
            .entrySet().parallelStream()
            .map(data -> new Tuple2<>(data.getKey(),
                    data.getValue().parallelStream().mapToDouble(value -> value.doubleValue()).sum()))
            .collect(Collectors.toList());

    return sum;
}

From source file:com.create.validation.PropertyValidationErrorsProvider.java

private Map<String, List<String>> getPropertyValidationErrorsGroupedByNestedPath(
        List<ObjectError> objectErrors) {
    return objectErrors.stream().map(this::toPropertyValidationError)
            .collect(Collectors.groupingBy(PropertyValidationError::getNestedPath,
                    Collectors.mapping(PropertyValidationError::getMessage, Collectors.toList())));
}

From source file:eu.cloudwave.wp5.feedbackhandler.aggregations.strategies.SimpleRequestAggregationStrategyImpl.java

/**
 * {@inheritDoc}/*from  ww  w .j a va2 s.  c om*/
 */
@Override
public RequestAggregationValues aggregate(RequestCollector requests) {

    IntSummaryStatistics stats = requests.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values().stream().mapToInt(p -> toInt(p)).summaryStatistics();

    return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(), stats.getSum(),
            stats.getCount());
}

From source file:eu.cloudwave.wp5.feedbackhandler.repositories.aggregations.AggregatedMicroserviceClientRequest.java

public IntSummaryStatistics getStatistics() {
    // Map<Date, Long> groupedRequests = microserviceClientRequest.getReqTimestamps().stream()
    // .collect(Collectors.groupingBy(timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
    // Collectors.counting()));

    return microserviceClientRequest.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values().stream().mapToInt(p -> toInt(p)).summaryStatistics();
}