Skip to content
Le Thanh NGUYEN edited this page Jan 21, 2016 · 4 revisions

Streaming/Grouping/Reducing

List -> Map of Map of U with even a reduction in the value U (List -> single Object)

list.stream()
    .collect(Collectors.groupingBy(item -> item.getCity(), // first key
                Collectors.groupingBy(item -> item.getLastName(), // second key
                    Collectors.reducing(an_instance_of_object_T,
                       BinaryOperator.maxBy(Comparator.comparing(T::getBirthDate))))));	

List -> reduce to a List with grouping criteria (same as above but get only the values in Map of Map

list.stream()
    .collect(Collectors.groupingBy(item -> item.getCity()))
    .entrySet().stream().map(entry -> entry.getValue().stream()
                            .collect(Collectors.groupingBy(item -> item.getLastName()))
                            .values() // list of list
                            .stream().map(items -> items.stream()
                                    .max(Comparator.comparing(T::getBirthDate)).get())
                            .collect(Collectors.toList()))
    .flatMap(Collection::stream).collect(Collectors.toList()); // join multiple list

List<List> -> List

list.stream().flatMap(Collection::stream).sorted(a_comparator_if_need)
                .collect(Collectors.toList());