Limit Realm results

前端 未结 4 548
情深已故
情深已故 2020-12-16 19:49

How do I limit the amount of objects Realm returns? .findAll returns all rows matching the query and .findFirst returns only the first. But what about something like first 1

相关标签:
4条回答
  • 2020-12-16 20:03

    The cool thing is that you don't need to worry about that with Realm. The result object returned from a query is lazily loading the objects and its fields when you access them. Your objects are never copied and thus only represented once in memory/disk.

    The (current) implementation detail of this is that the RealmResults object returned from a query is just a list of references to the matching objects. Those references are tiny numbers which are stored compressed so they take up very little memory. So even with 100.000 matches it actually wouldn't take up much memory. And it would take up the same amount of memory for all kind of objects, whether they have one int field or hundreds of fields with strings or big binaries.

    0 讨论(0)
  • 2020-12-16 20:14

    I figured out the solution to achieve this after so many days using "between" query as found in the official docs https://realm.io/docs/java/latest

    If you want to fetch first N elements, Simply pass the count from and to with field name as below

    realm.where(clazz).between("count",0,1000).findAll();
    

    Where,

    "count" = Field name (i.e variable name in your pojo)
    "0" = Range From
    "1000" = Range to

    For example: The above query will fetch first 0 to 1000 as RealmResults.

    Note: The above solution works only if you have some unique id with row count. In my case I manually inserted row count value before inserting the values into Realm.

    0 讨论(0)
  • 2020-12-16 20:17

    Realm currently do not provide any limit function but if you want first N elements

    int N=10;   // whatever value you want
    Realm mRealm=Realm.getDefaultInstance();
    
    RealmResults<Example> list= mRealm.where(Example.class).findAll();
    list.subList(0,N);
    

    for last N elements

    RealmResults<Example> list= mRealm.where(Example.class).findAll();
    list.subList(list.size()-N,list.size());
    
    0 讨论(0)
  • 2020-12-16 20:25

    One way could be this, if you really want only RealmResults, using Stream limit method:

    //get all results of your choice query
    RealmResults<TypeClass> entities = realm.where(TypeClass.class).findAll();
    //limit using Stream
    List<Integer> ids = Stream.of(entities).limit(10).map(x -> x.Id).collect(Collectors.toList());
    //return only those ids elments
    return realm.where(TypeClass.class).in("Id", ids.toArray(new Integer[])).findAll();
    
    0 讨论(0)
提交回复
热议问题