Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating a list of Strings in Java [duplicate]

Tags:

java

iterator

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.

like image 805
Zeus Avatar asked Dec 24 '22 08:12

Zeus


1 Answers

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 the CharSequence 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.

like image 101
Tunaki Avatar answered Jan 10 '23 18:01

Tunaki