Kavin-K
Kavin-K

Reputation: 2117

How to separate until last element of ArrayList in android

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

Answers (5)

user2999846
user2999846

Reputation:

Replace the for loop with this,

tempSeats = TextUtils.join(", ",userSelectedSeats);

Hope it helps!

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56443

A simple String.join will accomplish the task at hand.

String result = String.join(", ", userSelectedSeats);

Upvotes: 1

user8563382
user8563382

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

Ryan
Ryan

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

Mureinik
Mureinik

Reputation: 311723

Let Java's streams do the heavy lifting for you:

String tempSeats = userSelectedSeats.stream().collect(Collectors.joining(", "));

Upvotes: 3

Related Questions