I'm iterating through a list of list of strings. I need to print each list in comma separated format except the last element. This is my code.
for(Iterator itr = list.iterator(); itr.hasNext();){
List<String> l = (List<String>) itr.next();
for(Iterator it = l.iterator(); it.hasNext();){
System.out.print(it.next() + " ");
}
System.out.println();
}
This prints something like
listen, silent, tinsel,
How do I format the print logic to remove the comma after the last element. I can do that on for i
loop checking the value of i
against the last index, but wish to know how to do it with an Iterator
in Java.
Using Java 8, you don't to write any loop, you can just use String.join(delimiter, elements)
:
Returns a new
String
composed of copies of theCharSequence
elements joined together with a copy of the specified delimiter.
A sample code would be:
for(Iterator<List<String>> itr = list.iterator(); itr.hasNext();){
List<String> l = itr.next();
String str = String.join(", ", l);
System.out.println(str);
}
With such code, you don't need to worry about removing the last delimiter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With