如何从具有不同结果的领域数据库中查询 java

how to query from realm database with distinct results java

我有一个 Realm 对象 class,并在其中存储大量数据,假设我有一个 String uid; 字段。我想获得 uid 名称,但在相同的 uid 名称上只有一次, 例如

uid

AA

AA

BB

CC

DD

BB

BB

我只想得到 机管局,

BB,

抄送,

DD.

只有一次。 我查看了领域文档,但找不到任何内容。

感谢您的回答。

更新:

您可以使用 distinct() 获取对象的不同条目 class。

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

注意: .distinct 仅适用于索引的字段(@Index 或@PrimaryKey)。 它不适用于子对象 属性.

您可以在官方文档中找到有关此方法的更多信息。 https://realm.io/docs/java/latest/api/io/realm/Realm.html#distinct-java.lang.Class-java.lang.String-][1]

请使用以下步骤在 Realm 上进行区分

将您的领域版本更新为领域:1.2.0。因为在旧版本中 distinct 无法正常工作。

将@Index 属性 添加到要应用不同的变量

像这样执行你的查询

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

要在项目中包含领域依赖项,您可以在 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
    }
}

以上代码已经过测试并且可以正常工作

其他答案基本正确,但仍不完整。

其他解决方案需要使用 .findAll() 以便 return 值保持 RealmResult 类型。

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

在领域-gradle-plugin:6.0.2,