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.
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 Collection
s, not only List
s 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With