Reputation: 2117
I need to assign an ArrayList's data into a String variable.
Using following code I am getting tempSeats
equals jack, ravi, mike,
ArrayList<String> userSelectedSeats = new ArrayList<String>();
userSelectedSeats.add("jack");
userSelectedSeats.add("ravi");
userSelectedSeats.add("mike");
for (String s : userSelectedSeats) {
tempSeats += s + ", ";
}
but output should be jack, ravi, mike
What modification should I do to my code?
Upvotes: 1
Views: 63
Reputation:
Replace the for loop with this,
tempSeats = TextUtils.join(", ",userSelectedSeats);
Hope it helps!
Upvotes: 0
Reputation: 56443
A simple String.join
will accomplish the task at hand.
String result = String.join(", ", userSelectedSeats);
Upvotes: 1
Reputation:
String c;
ArrayList<String> userSelectedSeats = new ArrayList<String>();
userSelectedSeats.add("jack");
userSelectedSeats.add("ravi");
userSelectedSeats.add("mike");
for (int i=0; i < userSelectSeats.length(); i++)
c += userSelectSeats.get(i).toString()+ ",";
Upvotes: 0
Reputation: 201
You're adding a comma after the end of every item, even the last item. You only want to add a comma if the item isn't the last item in the list. This is called joining.
If you're using Java 8, you can do
userSelectedSeats.stream().collect(Collectors.joining(", "))
Otherwise see this question for further info.
Upvotes: 1
Reputation: 311723
Let Java's streams do the heavy lifting for you:
String tempSeats = userSelectedSeats.stream().collect(Collectors.joining(", "));
Upvotes: 3