If I have a list of values, is there an easy way to get all the RealmObject where a certain field has one of the values in my list?
For example:
List<String> ids = Arrays.asList("id1", "id2", "id3"); // Or simply an array
realm.where(MyObject.class).in("myField", ids).findAll(); // Return all MyObject where myField is equal to "id1" or "id2" or "id3"
Or do I have to loop through those values and use beginGroup().or() [...] .endGroup()?
There is no easy way unfortunately, but we are tracking the feature request here: https://github.com/realm/realm-java/issues/841
Until then the way to do it would be:
RealmQuery<MyObject> query = realm.where(MyObject.class);
for (String id : ids) {
query.or().equalTo("myField", id);
}
RealmResults<MyObject> results = query.findAll();
Sorry for not searching first...
Thank you for your answer.
@cmelchior I was looking for the same thing and came across your workaround. Should't it be query.or().equalTo("myField", id);?
@meierjan
Ups! Yes, you are right.
@cmelchior
Proposed solution seems to be not generic enough, it crashes with java.lang.UnsupportedOperationException: Missing right-hand side of OR in case of one single id, since it results into realm.where(MyObject.class).or().equalTo("myField", id).findAll() I believe. You would need to check the first id separately.
Anyway, in() operator seems to be already implemented in latest versions, got confused by #841 which is still opened.
public RealmQuery<E> in(String fieldName, String[] values) {
if (values == null || values.length == 0) {
throw new IllegalArgumentException(EMPTY_VALUES);
}
beginGroup().equalTo(fieldName, values[0]);
for (int i = 1; i < values.length; i++) {
or().equalTo(fieldName, values[i]);
}
return endGroup();
}
@Ghedeon This is the general solution
Most helpful comment
There is no easy way unfortunately, but we are tracking the feature request here: https://github.com/realm/realm-java/issues/841
Until then the way to do it would be: