Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 for each and first index

Anyone knows how to achieve following piece code in a Java 8 way respectively is there any stream methods to detect the first element in a forEach?

List<String> myList = new ArrayList<String>();
myList.add("A");
myList.add("B");

int i = 0;

for (final String value : myList) {
   if (i == 0) {
     System.out.println("Hey that's the first element");
   }

   System.out.println(value);

   i++;
 }

Java8:

myList.stream().forEach(value -> {
  // TODO: How to do something special for first element?

  System.out.println(value);
});

Furthermore, let's says that the goal is the following (console output):

A    Something special
B
C
D
E
F
like image 302
David Dal Busco Avatar asked Mar 24 '17 09:03

David Dal Busco


People also ask

Is there a way to access an iteration counter in Java forEach loop?

Adding a Counter to forEach with Stream Let's try to convert that into an operation that includes the counter. This function returns a new lambda. That lambda uses the AtomicInteger object to keep track of the counter during iteration. The getAndIncrement function is called every time there's a new item.


1 Answers

May this work for you?

myList.stream().findFirst().ifPresent(e -> System.out.println("Special: " + e));
myList.stream().skip(1).forEach(System.out::println);

Output:

Special: A
B

Alternative:

myList.stream().findFirst().ifPresent(e -> somethingSpecial(e));
myList.stream().forEach(System.out::println);
like image 85
Oneiros Avatar answered Sep 20 '22 18:09

Oneiros