我想把这个java do...while()转换成Java8。
private static final Integer PAGE_SIZE = 200;
int offset = 0;
Page page = null;
do {
// Get all items.
page = apiService.get(selector);
// Display items.
if (page.getEntries() != null) {
for (Item item : page.getEntries()) {
System.out.printf("Item with name '%s' and ID %d was found.%n", item.getName(),
item.getId());
}
} else {
System.out.println("No items were found.");
}
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
} while (offset < page.getTotalNumEntries());这段代码对apiService进行api调用并检索数据。然后,我想要循环,直到偏移量小于totalNumberEntries。
阻止我使用while()、foreach with step或any other kind of loop循环的原因是,如果不进行while()调用(这是在循环中完成的),我就不知道totalNumberEntries。
我能想到的一种选择是进行API调用,只是为了获得totalNumberEntries并继续循环。
发布于 2016-04-25 22:14:03
如果您确实想要/需要一个stream api来检索页面,您可以通过实现一个在tryAdvance()方法中检索每个页面的拆分器来创建您自己的流。
它看起来就像这样
public class PageSpliterator implements Spliterator<Page> {
private static final Integer PAGE_SIZE = 200;
int offset;
ApiService apiService;
int selector;
Builder builder;
Page page;
public PageSpliterator(ApiService apiService) {
// initialize Builder?
}
@Override
public boolean tryAdvance(Consumer<? super Page> action) {
if (page == null || offset < page.getTotalNumEntries()) {
Objects.requireNonNull(action);
page = apiService.get(selector);
action.accept(page);
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
return true;
} else {
// Maybe close/cleanup apiService?
return false;
}
}
@Override
public Spliterator<Page> trySplit() {
return null; // can't split
}
@Override
public long estimateSize() {
return Long.MAX_VALUE; // don't know in advance
}
@Override
public int characteristics() {
return IMMUTABLE; // return appropriate
}
}然后你可以像这样使用它:
StreamSupport.stream(new PageSpliterator(apiService), false)
.flatMap(page -> page.getEntries()
.stream())
.forEach(item -> System.out.printf("Item with name '%s' and ID %d was found.%n", item.getName(), item.getId()));发布于 2016-04-21 17:29:39
在我看来,do...while循环是最佳选择的场景并不多见。然而,这就是这样一个场景。
仅仅因为Java8中有新东西,并不意味着您必须使用它。如果你仍然想用foreach循环来实现它,不管是什么原因,那么我会选择你提到的那个选项。在开始时执行API调用,然后启动foreach。
https://stackoverflow.com/questions/36765214
复制相似问题