java - what's a simple and elegant way to print arraylist elements separated by comma? -


hi i'm writing code print elements arraylist separated comma, folllowing method wrote. works. i'm wondering if can simplified? , there more elegant way print elements arraylist separated delimiter? (e.g. method prints arraylist of strings "tom, sherlock, jack")

thanks everyone!

public string printmyarraylist() {     if(mylist.size() == 0)return "";     else if(mylist.size() == 1)return mylist.get(0).tostring();     else {         string returnstr = "";         (int = 0; < mylist.size() ; i++) {             if(i == 0)returnstr = mylist.get(i).tostring();             else {                 returnstr = returnstr + ", " + mylist.get(i).tostring();             }         }         return returnstr;     } } 

using collectors.joining java 8:

return list.stream()            .map(object::tostring)            .collect(collectors.joining(", ")); 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -