Separating strings from an Arraylist with comma

Asked

Viewed 3,247 times

2

I don’t have much knowledge of Java, I would like to separate the string 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 didn’t find a good solution, I tried with the foreach of Java 8, but I could not.

  • 1

    Have you ever tried to do something like String.join(", ", nomes)?

  • Only to display on screen? If yes, just System.out.println(nomes); see: https://ideone.com/f0yjBL

  • Was that right.

2 answers

7


No need for a loop, the class itself String has a method called join that converts a list into 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), will have on screen: Paulo, Ana, Zeno, Beno.

See working on Ideone.

  • String All Men, Shouldn’t Be An Array?

  • In this case, no, because from what I understood of the question you want to display (or get) a string with all names separated by comma and that’s exactly what this code does.

4

If it’s just to display on the screen, you don’t need to use any special command type, just display by the standard java text output:

System.out.println(nomes);

Exit:

[Paulo, Ana, Zeno, Beno]

This is the default Arraylist display, defined by your method toString(), as can be 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(", ");
        }
    }
}

Functioning in the ideone.com/f0yjBL

Browser other questions tagged

You are not signed in. Login or sign up in order to post.