如何通过LocalDate对磁通元素进行分组?

时间:2019-07-12 22:23:06

标签: spring reactive-programming spring-webflux project-reactor

给出Flux<Event>,其中事件是:

data class Event(val eventDate: LocalDate, val data: String)

考虑到某些元素发生在完全相同的LocalDate上,我想按事件日期的升序对它们进行分组。

目标是最终得到类似Flux<GroupedEvent>的图形,其中GroupedEvent是:

data class GroupedEvent(val eventDate: LocalDate, val data: List<String>)

通知data: List<String>将包含在同一LocalDate发生的所有数据。

这怎么办?

1 个答案:

答案 0 :(得分:0)

对于给定的数据结构:

public class GroupedEvent {
    private LocalDate localDate;
    private List<String> data;
}
public class Event {
    private LocalDate eventDate;
    private String data;
}

您可以尝试这种方式:

        List<Event> data = Arrays.asList(
                new Event(LocalDate.of(2019, 1, 1), "A"),
                new Event(LocalDate.of(2019, 1, 2), "B"),
                new Event(LocalDate.of(2019, 1, 3), "C"),
                new Event(LocalDate.of(2019, 1, 1), "D"),
                new Event(LocalDate.of(2019, 2, 1), "E")
        );

        Flux<Event> eventFlux = Flux.fromIterable(data);
        Flux<GroupedFlux<LocalDate, Event>> groupedFluxFlux = eventFlux.groupBy(Event::getEventDate);
        groupedFluxFlux.flatMap(groupedFlux ->
                groupedFlux
                        .map(Event::getData)
                        .collectList()
                        .map(list -> new GroupedEvent(groupedFlux.key(), list))
        )
                .sort(Comparator.comparing(GroupedEvent::getLocalDate))
                .doOnNext(groupedEvent -> System.out.println(groupedEvent.getLocalDate() + " -> " + groupedEvent.getData()))
                .subscribe();