一種方法是
Spliterator<String> sp = getDummyList().spliterator();
if(sp.tryAdvance(token -> System.out.println("this is first token: "+token))) {
StreamSupport.stream(sp, false).forEach(System.out::println);
}
與任意Collection
S,不僅List
的作品,並有可能比skip
基礎的解決方案時更有效更先進的Stream
操作鏈接在一起。這種模式也適用於一個Stream
源,即當多次遍歷不可能或者可能產生不同結果時。
Spliterator<String> sp=getDummyList().stream().filter(s -> !s.isEmpty()).spliterator();
if(sp.tryAdvance(token -> System.out.println("this is first non-empty token: "+token))) {
StreamSupport.stream(sp, false).map(String::toUpperCase).forEach(System.out::println);
}
然而,第一個元素的特殊待遇仍可能會導致性能損失,相對於同樣處理所有的流元素。
如果你想要做的就是將像forEach
一個動作,你也可以使用一個Iterator
:
Iterator<String> tokens = getDummyList().iterator();
if(tokens.hasNext())
System.out.println("this is first token:" + tokens.next());
tokens.forEachRemaining(System.out::println);
我認爲你的做法已經乾淨簡潔:) – TheLostMind
有一件事我會做,以防止NPE也檢查'tokens'是否爲'null' – TheLostMind
是的,這只是虛擬代碼來解釋問題。我想知道是否有一些方法可以合併,如果條件內的流式調用,並減少更多的行數。 –