Performing specific operation on first element of list using Java8 streaming

风格不统一 提交于 2019-12-05 04:07:55
Holger

One way to express the intention is

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

which works with arbitrary Collections, not only Lists and is potentially more efficient than skip based solutions when more advanced Stream operations are chained. This pattern is also applicable to a Stream source, i.e. when multiple traversal is not possible or could yield two different results.

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

However, the special treatment of the first element might still cause a performance loss, compared to processing all stream elements equally.

If all you want to do is applying an action like forEach, you can also use an Iterator:

Iterator<String> tokens = getDummyList().iterator();
if(tokens.hasNext())
    System.out.println("this is first token:" + tokens.next());
tokens.forEachRemaining(System.out::println);

would this be cleaner

    items.stream().limit(1).forEach(v -> System.out.println("first: "+ v));
    items.stream().skip(1).forEach(System.out::println);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!