2016-04-21 50 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()));