2

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 ?

Alex DG
  • 1,859
  • 2
  • 22
  • 34
  • It should be, since `DiscreteDomain` is an abstract class... However your custom object doesn't seem like it will allow you to implement the `next()` and `previous()` method of this class. Having the code of that class would allow a more detailed answer. – fge Apr 13 '15 at 11:11

1 Answers1

7

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 to ContiguousSet.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);
  }
}
assylias
  • 321,522
  • 82
  • 660
  • 783