java - what's a simple and elegant way to print arraylist elements separated by comma? -
this question has answer here:
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
Post a Comment