一种方法是
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
是的,这只是虚拟代码来解释问题。我想知道是否有一些方法可以合并,如果条件内的流式调用,并减少更多的行数。 –