ILyaCyclone icon

groupFlatRows

ILyaCyclone | PRO | 07/01/19 07:24:43 AM UTC | 0 ⭐ | 721 👁️ | Never ⏰ | []
Java |

1.11 KB

|

None

|

0 👍

/

0 👎

/**
 R - flat Row
 P - Parent class
 C - Child class
 */
public <R, P, C> List<P> groupFlatRows(Collection<R> rows
            , Function<R, P> mapRowToParent
            , Function<R, C> mapRowToChild
            , BiConsumer<P, List<C>> setParentChildren
            , Comparator<P> sortParents) {
        // преобразовываем Collection<P> в Map<P, List<C>>
        return rows.stream()
                .collect(groupingBy(mapRowToParent
                        , mapping(mapRowToChild
                                , Collectors.toList())))
                // преобразовываем Map<P, List<C>> в List<P>, устанавливая дочерний List<C> в каждый P
                .entrySet().stream()
                .map(entry -> {
                    P parent = entry.getKey();
                    List<C> children = entry.getValue();
                    setParentChildren.accept(parent, children);
                    return parent;
                })
                // Stream<P>
                .sorted(sortParents)
                .collect(Collectors.toList());
    }

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎