Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading