问题
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.
回答1:
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);
回答2:
would this be cleaner
items.stream().limit(1).forEach(v -> System.out.println("first: "+ v));
items.stream().skip(1).forEach(System.out::println);
来源:https://stackoverflow.com/questions/40625519/performing-specific-operation-on-first-element-of-list-using-java8-streaming