Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing specific operation on first element of list using Java8 streaming

I want to perform certain operation on first element of my list and different operation for all remaining elements.

Here is my code snippet:

List<String> tokens = getDummyList();
if (!tokens.isEmpty()) {
    System.out.println("this is first token:" + tokens.get(0));
}
tokens.stream().skip(1).forEach(token -> {
    System.out.println(token);
});

Is there any more cleaner way to achieve this preferably using java 8 streaming API.

like image 751
vatsal mevada Avatar asked Nov 16 '16 06:11

vatsal mevada


1 Answers

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);
like image 187
Holger Avatar answered Nov 15 '22 17:11

Holger