Performing a specific operation on the first element of a list using Java8 streaming

I want to perform a specific operation on the first element of my list and another operation for all other 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 a cleaner way to achieve this, preferably using the java 8 streaming API.

+7
source share
2 answers

it will be cleaner

  items.stream().limit(1).forEach(v -> System.out.println("first: "+ v)); items.stream().skip(1).forEach(System.out::println); 
+5
source

One way to express an intention

 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 , not just with List and is potentially more efficient than skip solutions when more complex Stream operations are combined. This pattern is also applicable to the Stream source, i.e. when multiple bypass is impossible or can give 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, special processing of the first element may still cause a performance loss compared to the same processing of all stream elements.

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

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

Source: https://habr.com/ru/post/1259806/


All Articles