Reputation: 1869
I'm wondering if it's possible to use Guava Range to iterate on a list of custom objects.
I have this example, which should get an interval of 5 items in a list:
Range<CustomObject> range = Range.closed(customObjectList.get(Auxiliar.index), customObjectList.get(Auxiliar.index + 4));
And then I would like to iterate on this range to get my list of object, I mean, to be able to do something like that:
List<CustomObject> list = new ArrayList<CustomObject>();
for(CustomObject c : range){
list.add(c)
}
At the moment I can't do this foreach on a Guava Range, instead I have to do that like here:
for(int grade : ContiguousSet.create(yourRange, DiscreteDomain.integers())) {
...
}
But here the problem is, I can't use DiscreteDomain.CustomObject().
Is there a way to use this Guava Range with a list of CustomObject ?
Upvotes: 2
Views: 927
Reputation: 328923
If you read Range
's javadoc:
Note that it is not possible to iterate over these contained values. To do so, pass this range instance and an appropriate
DiscreteDomain
toContiguousSet.create(com.google.common.collect.Range<C>, com.google.common.collect.DiscreteDomain<C>)
.
So your approach is correct, except that you need to create a custom DiscreteDomain
for your custom object:
public class CustomDiscreteDomain extends DiscreteDomain<CustomObject> {
//override and implement next, previous and distance
}
This may or may not be practical depending on what those objects are.
Simplistic example with a LocalDate
(would probably need additional bound checking, null checking etc.):
public static class LocalDateDiscreteDomain extends DiscreteDomain<LocalDate> {
@Override public LocalDate next(LocalDate value) {
return value.plusDays(1);
}
@Override public LocalDate previous(LocalDate value) {
return value.minusDays(1);
}
@Override public long distance(LocalDate start, LocalDate end) {
return DAYS.between(start, end);
}
}
Upvotes: 7