How to control peek to treat the last element differently?

  • A+
Category:Languages

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?

 


There's likely a duplicate or two out there, but if you don't specifically need to use peek(), just do something like:

String str = "abcd"; char[] arr = str.toCharArray(); for (int i = 0; i < arr.length; i++) {     System.out.print((i == str.length() - 1) ? arr[i] + "/n" : arr[i] + ":"); } 

Output:

a:b:c:d

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: