Separate strings from an ArrayList with comma

2

I do not have much knowledge of Java, I would like to separate the strings from my List, with ",".

List<String> nomes = Arrays.asList("Paulo", "Ana", "Zeno", "Beno");

for(int i=0; i<nomes.size(); i++) {
    System.out.format("%s%s", nomes.get(i), 
        i != nomes.size() - 1 ? ", " : " ");
}

But I did not find a good solution, I also tried with foreach of Java 8, but I could not.

    
asked by anonymous 06.05.2017 / 20:16

2 answers

6

You do not need any loopback, the String class itself has a method called join that converts a list to string , using another string as a separator .

List<String> nomes = Arrays.asList("Paulo", "Ana", "Zeno", "Beno");
String todosNomes = String.join(", ", nomes);

If you do System.out.println(todosNomes) , you will have: Paulo, Ana, Zeno, Beno .

  

See working at Ideone .

    
06.05.2017 / 20:36
4

If it's just to display on the screen, you do not need to use any kind of special command, just display it by default java text output:

System.out.println(nomes);

Output:

  

[Paul, Ana, Zeno, Beno]

This is the default view of the ArrayList, defined by its toString() method, as seen below (taken from grepcode )

 public String toString() {
        Iterator<E> i = iterator();
        if (! i.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = i.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! i.hasNext())
                return sb.append(']').toString();
            sb.append(", ");
        }
    }
}

Running on ideone.com/f0yjBL

    
06.05.2017 / 20:39