gpt4 book ai didi

java - 在RxJava2中groupBy之后如何获取类中的原始元素?

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:22 24 4
gpt4 key购买 nike

我有一个 JSON 元素列表。例如,每个 JSON 元素都表示为名为“Foo”的 Java 类。这个 Foo 类还有其他字段,它们也是 Java 类。我尝试按 Bar id 对这些 Foo 元素进行分组,然后我想对分组元素执行其他操作,例如过滤、排序。

public class Foo {
private int id;
private Bar bar;
private Baz baz;
private int qty;
}

public class Bar {
private int id;
private String name;
}

public class Baz {
private int id;
private String type;
}

我尝试了类似的方法来查看 groupBy 操作后的结果,但它没有打印任何内容。但是,如果我提供简单的元素(如 String 或 Integer)而不是 Foo 并尝试使用相同的方法对它们进行分组,它就会起作用。

List<Foo> myInput = new ArrayList<>();
myInput.add(...);
myInput.add(...);
Observable.fromIterable(myInput)
.groupBy(el -> el.getBar().getId())
.concatMapSingle(Observable::toList)
.subscribe(System.out::println);

此代码使用此输入并随后打印出分组元素:

Observable<String> animals = Observable.just(
"Tiger", "Elephant", "Cat", "Chameleon", "Frog", "Fish", "Flamingo");

animals.groupBy(animal -> animal.charAt(0))
.concatMapSingle(Observable::toList)
.subscribe(System.out::println);

我想做的是这样的:

Observable.fromIterable(myInput)
.filter(el -> el.getBaz().getType().equals("type1"))
.groupBy(el -> el.getBar().getId())
//.filter(...)
//.sorted(...)

如何对元素进行分组并检索分组的元素并对其应用其他操作?您能否解释一下,以便我能够理解幕后发生的事情?

最佳答案

来自 Observable#groupBy 的文档:

Groups the items emitted by an ObservableSource according to a specified criterion, and emits these grouped items as GroupedObservables.

来自GroupedObservable的文档:

An Observable that has been grouped by key, the value of which can be obtained with getKey().

因此,GroupedObservableObservable 的子类,因此您可以应用常用的 mapfilterflatMap 等可用运算符。

例如,如果您想对每个 Bar 分组的 Fooqty 进行求和,则可以按以下方式映射 GroupedObservable:

Observable.fromIterable(foos)
.groupBy(foo -> foo.getBar().getId())
.flatMapSingle(grouped -> grouped.map(foo -> foo.qty).reduce(0, Integer::sum))
.subscribe(System.out::println);

关于java - 在RxJava2中groupBy之后如何获取类中的原始元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com