Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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);
about 4 years ago · Santiago Trujillo Relatório

0

I don't think there is something provided in stream.

There are several alternatives you may consider:

Method 1:

int[] i = {0};  // I am using it only as an int holder.
myList.stream().forEach(value -> {
  if (i[0]++ == 0) {
    doSomethingSpecial;
  }
  System.out.println(value);
});

Method 2:

If your list is quick for random access (e.g. ArrayList), you may consider:

IntStream.range(0, myList.size())
  .forEach(i -> {
    ValueType value = myList.get(i);
    if (i == 0) {
      doSomethingSpecial();
    }
    System.out.println(value);
  });
about 4 years ago · Santiago Trujillo Relatório

0

Try StreamEx

StreamEx.of("A", "B", "C") //
        .peekFirst(e -> System.out.println(e + " Something special")).skip(1) //
        .forEach(System.out::println);
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda