简体   繁体   中英

how to query from realm database with distinct results java

I have got a Realm object class, and storing lots of data in there, imagine that I have a String uid; field. I want to get uid names, but on same uid names just only one time, For example

uid

AA

AA

BB

CC

DD

BB

BB

I want to get just AA,

BB,

CC,

DD.

Only one time. I looked over realm documentation but couldn't find anything.

Thanks for answers.

UPDATED :

You can use distinct() to get distinct entries for an object class.

// Returns the set of users that all have a different name
RealmResults<User> users = realm.where(User.class).distinct("name");

Note: .distinct will only work on fields that are indexed (@Index or @PrimaryKey). It doesn't work with child object property.

You can find more information about this method here in the official documentation. https://realm.io/docs/java/latest/api/io/realm/Realm.html#distinct-java.lang.Class-java.lang.String-][1]

Please use below steps to work distinct on Realm

Update your realm version to realm :1.2.0 . because in older version distinct not working properly.

add @Index property to variable on which you want to apply distinct

execute your query like this

RealmResult<Example> realmReault =realm.where(Example.class).distinct("uid");

to include realm dependency in your project you can add below line in build.gradle(Project)

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'

        classpath "io.realm:realm-gradle-plugin:1.2.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Above code is tested and working properly

The other answers are almost correct, but still incomplete.

The other solutions need to use .findAll() so that the return value remain RealmResult type.

RealmResult<Example> realmReault =realm.where(Example.class).distinct("uid").findAll();

On realm-gradle-plugin:6.0.2,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM