如何过滤RXJava中observable发出的重复值? [英] How to filter duplicate values emitted by observable in RXJava?

查看:443
本文介绍了如何过滤RXJava中observable发出的重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象集合,我想在其中隐藏重复项。我知道不同运算符,但是如果我没有记错的话,它会通过适当覆盖的哈希码方法比较项目。但是,如果我的哈希码为相同的对象返回不同的值,而我想自己设置相等,该怎么办。独特的有2个重载方法-一个没有参数,一个有Func1参数,我想我应该使用第二种方法,但是如何实现呢?

  .distinct(new Func1< ActivityManager.RunningServiceInfo,Object>(){
@Override
公共对象调用(ActivityManager.RunningServiceInfo runningServiceInfo){
返回null;
}
})


解决方案

是的,您说的对需要对对象具有一致的 equals() hashcode()方法,才能使用 distinct(),因为在 distinct 运算符的内部使用了 HashSet 。 / p>

带有$ Func1 distinct 版本将对象转换为想要与众不同的对象(但必须实现一致的 equals hashcode 方法)。



假设我有一个 Observable< Person> ,其中 Person 像这样:

  class Person {
String firstName;
字符串lastName;
}

然后计算不同名字的数量,我可以这样做:

  persons.distinct(person-> person.firstName).count(); 


I have a collection of objects, where i want to suppress duplicate items. I know about Distinct operator, 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(new Func1<ActivityManager.RunningServiceInfo, Object>() {
                        @Override
                        public Object call(ActivityManager.RunningServiceInfo runningServiceInfo) {
                            return null;
                        }
                    })

解决方案

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.

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).

Suppose I have an Observable<Person> where Person is like this:

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();

这篇关于如何过滤RXJava中observable发出的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆