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

144
Visualizações
How to modify elements inside List using stream and ignore last element?

I have the following list:

var list = Arrays.asList("a", "b", "c");

I want to achieve something like that:

// "a, "
// "b, "
// "c"

So I did that:

var formattedList = list.stream()
        .map(el -> el + ", ")
        .collect(Collectors.toList());

It is working almost fine:

// "a, "
// "b, "
// "c, "

but as you can see I don't know how to "ommit" last element in my stream.

Could someone help me achieve that?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Tahas answer is great if you have a list, but if you for some use case have a stream you can just just do.

String result = list.stream()
    .collect(Collectors.joining(","));
over 4 years ago · Santiago Trujillo Relatório

0

You could use .limit() to limit the elements of the original list that are streamed:

        Stream.concat(
                list.stream().map(el -> el + ", ").limit(list.size() - 1),
                Stream.of(list.get(list.size() - 1)))
            .collect(Collectors.toList());
over 4 years ago · Santiago Trujillo Relatório

0

You can use String.join()

var list = Arrays.asList("a", "b", "c");
String.join(",", list) // returns a,b,c

I assumed you wanted to join the elements. But if you don't, I think stream api is not suitable for this. Traditional iterator would work better. Because your requirement is based on index of the element. In streams, index information is not provided.

over 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