Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!