Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control peek to treat the last element differently?

I have a stream of characters like

"abcd".chars()

I am using peek to print out stream like this

"abcd".chars().peek(e->System.out.print(e + ":"))

The only problem is that it print out as

a:b:c:d:

I would like to replace the last colon with newline, but don't know how to do that, anyone could help?

like image 392
Robert Li Avatar asked Dec 03 '22 19:12

Robert Li


1 Answers

Using the joining collector is another option:

String result = Arrays.stream(string.split(""))
                      .collect(Collectors.joining(":"));

or:

String result = Pattern.compile("")
                       .splitAsStream(string)
                       .collect(Collectors.joining(":"));

if you actually want a new line then use this overload of the joining collector

Collectors.joining(":","","\n")
like image 183
Ousmane D. Avatar answered Dec 15 '22 00:12

Ousmane D.