我有一个对象集合,我想在其中抑制重复的项目。我知道关于Distinct http://reactivex.io/documentation/operators/distinct.html运算符,但如果我没有记错的话,它会通过正确覆盖的哈希码方法来比较项目。但是,如果我的哈希码为同一对象返回不同的值,并且我想自己设置相等性,该怎么办? unique 有 2 个重载方法 - 一种没有参数,一种带有 Func1 参数,我想我应该使用第二种方法,但是精确度如何?
.distinct(new Func1<ActivityManager.RunningServiceInfo, Object>() {
@Override
public Object call(ActivityManager.RunningServiceInfo runningServiceInfo) {
return null;
}
})
是的,你是对的,你需要保持一致equals()
and hashcode()
您的对象上能够使用的方法distinct()
因为在幕后distinct
运算符使用HashSet
.
的版本distinct
with a Func1
允许您将对象转换为您想要不同的对象(但必须实现一致equals
and hashcode
方法)。
假设我有一个Observable<Person>
where Person
是这样的:
class Person {
String firstName;
String lastName;
}
然后要计算不同名字的数量,我可以这样做:
persons.distinct(person -> person.firstName).count();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)