将番石榴范围与自定义对象一起使用

Use Guava Range with custom object

我想知道是否可以使用 Guava Range 迭代自定义对象列表。

我有这个例子,它应该在列表中获得 5 个项目的间隔:

Range<CustomObject> range = Range.closed(customObjectList.get(Auxiliar.index), customObjectList.get(Auxiliar.index + 4));

然后我想在这个范围内迭代以获得我的对象列表,我的意思是,能够做类似的事情:

List<CustomObject> list = new ArrayList<CustomObject>();
for(CustomObject c : range){
    list.add(c)
}

目前我不能在 Guava Range 上做这个 foreach,相反我必须像 here:

那样做
for(int grade : ContiguousSet.create(yourRange, DiscreteDomain.integers())) {
  ...
}

但这里的问题是,我不能使用 DiscreteDomain.CustomObject()。

有没有办法将这个 Guava Range 与 CustomObject 列表一起使用?

如果您阅读了 Range 的 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>).

所以你的方法是正确的,除了你需要为你的自定义对象创建一个自定义DiscreteDomain

public class CustomDiscreteDomain extends DiscreteDomain<CustomObject> {
  //override and implement next, previous and distance
}

这可能实用也可能不实用,具体取决于这些对象是什么。

带有 LocalDate 的简单示例(可能需要额外的绑定检查、空值检查等):

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);
  }
}