2016-04-21 76 views
0

我想转换这个用java做...而()到Java 8do ... while()使用Java 8流?

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

此代码API调用apiService和检索数据。然后,我想循环直到偏移量小于totalNumberEntries

什么是使用while()foreach with stepany other kind of loop循环,我不知道totalNumberEntries未做API调用(这是在循环内完成),禁止我。

我能想到的一个选择是进行API调用以获取totalNumberEntries并继续循环。

+8

'做{...}而(...)'是完全合法Java 8. –

+1

请分享你已经尝试过的 – sidgate

+2

从技术上讲,函数的方式将是Java 9中存在的'takeWhile' http://stackoverflow.com/a/32304570/1743880 – Tunaki

回答

1

在我看来,没有多少场景,其中do ... while循环将是最好的选择。然而,这是一种情况。

仅仅因为Java8中有新东西,并不意味着你必须使用它。 如果你仍然想用foreach循环来实现它,不管出于什么原因,那么我会选择你提到的选项。在开始时进行API调用,然后启动foreach。

2

如果您确实需要/需要用于检索页面的流api,您可以通过实施Spliterator在其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()));