java 如何过滤RXJava中observable发出的重复值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32286371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter duplicate values emitted by observable in RXJava?
提问by Lester
I have a collection of objects, where i want to suppress duplicate items. I know about Distinctoperator, but if i am not mistaken it compare items by properly overrided hashcode method. But what if my hashcode returns different values for same objects, and i want to set equality by my own. distinct have 2 overloaded methods - one without params and one with Func1 param,i suppose that i should use 2nd method, but how exaclty?
我有一组对象,我想在其中取消重复项。我知道Distinct运算符,但如果我没有记错的话,它会通过正确覆盖的哈希码方法比较项目。但是如果我的哈希码为相同的对象返回不同的值,并且我想自己设置相等性怎么办。distinct 有 2 个重载方法 - 一个没有参数,一个有 Func1 参数,我想我应该使用第二个方法,但具体如何?
.distinct(new Func1<ActivityManager.RunningServiceInfo, Object>() {
@Override
public Object call(ActivityManager.RunningServiceInfo runningServiceInfo) {
return null;
}
})
回答by Dave Moten
Yep you are right that you need to have consistent equals()
and hashcode()
methods on your object to be able to use distinct()
because under the covers the distinct
operator uses a HashSet
.
是的,你是正确的,你需要有一致equals()
和hashcode()
方法,你的对象上可以使用distinct()
,因为在幕后distinct
操作者使用HashSet
。
The version of distinct
with a Func1
allows you to convert the object into something that you want to be distinct (but must implement consistent equals
and hashcode
methods).
distinct
with a的版本Func1
允许您将对象转换为您想要与众不同的东西(但必须实现一致的equals
和hashcode
方法)。
Suppose I have an Observable<Person>
where Person
is like this:
假设我有一个Observable<Person>
wherePerson
是这样的:
class Person {
String firstName;
String lastName;
}
Then to count the number of distinct first names I could do this:
然后计算不同名字的数量,我可以这样做:
persons.distinct(person -> person.firstName).count();
回答by FriendlyMikhail
Not sure if simplest way but you can do it with reduce. Reduce takes a collection and an action. Within the action you are responsible for adding the elements to the collection yourself. There you can do whatever logic you'd like and conditionally add elements to the collection.
不确定是否是最简单的方法,但您可以使用 reduce 来实现。Reduce 需要一个集合和一个动作。在操作中,您负责自己将元素添加到集合中。在那里你可以做任何你想做的逻辑,并有条件地向集合中添加元素。