我想知道是否可以使用 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 上执行此操作,而是必须像 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
toContiguousSet.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
的简单示例(可能需要额外的绑定(bind)检查、空值检查等):
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);
}
}
关于java - 将 Guava 范围与自定义对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29603817/