How to filter duplicate values emitted by observable in RXJava?

后端 未结 2 544
南笙
南笙 2021-02-19 00:29

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 hashcod

2条回答
  •  无人共我
    2021-02-19 00:51

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

提交回复
热议问题