Saturday, April 27, 2019

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

Hi I'm writing code to print all elements from an ArrayList separated by comma, the folllowing is the method I wrote. It works. But i'm wondering if it can be simplified? And is there a more elegant way to print all elements from an ArrayList separated by some delimiter? (e.g. a method that prints an ArrayList of Strings get "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 = "";
for (int i = 0; i < mylist.size() ; i++) {
if(i == 0)returnStr = mylist.get(i).toString();
else {

returnStr = returnStr + ", " + mylist.get(i).toString();
}
}
return returnStr;
}
}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...