有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java降低反应器中的组通量

我有一个通量,其中包含不同的对象类型,我希望按类型对元素进行分组,然后减少每个组

下面是一个简单的代码来实现这一点

    Flux<Item> item=Flux.just(new Item("item1"), new Item("item2"));
    Flux<Item2> item2=Flux.just(new Item2(4.0f), new Item2(2.0f));

    Flux<Object> objects=Mono.empty().concatWith(item).concatWith(item2);       
    Flux<GroupedFlux<Object>> groups=objects.groupBy(value -> value.getClass());

如何按类型减少每个流量enter code here


共 (1) 个答案

  1. # 1 楼答案

    我在gitter上找到了解决方案。感谢@simonbasle和@osi的反应能力

    https://gitter.im/reactor/reactor

    关键是flatMap方法,并使用该方法区分值

    groups.flatMap(gf -> {
            if(gf.key()==Item.class) {
                return gf.reduce(new Item(""), (a, b) -> {
                    return new Item(a.getValue()+((Item)b).getValue());
                });
            }
            else if(gf.key()==Item2.class) {
                return gf.reduce(new Item2(0.0f), (a, b) -> {
                    return new Item2(a.getValueF()+((Item2)b).getValueF());
                });
            }
            throw new IllegalArgumentException("unknown key: "+gf.key());
        });