1

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?

Kavin-K
  • 1,948
  • 3
  • 17
  • 48

5 Answers5

3

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

String tempSeats = userSelectedSeats.stream().collect(Collectors.joining(", "));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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.

Ryan
  • 201
  • 1
  • 6
  • Woooow, that Stream thing is awesome, didn't know about it. Looks like LINQ but in Java, although more limited. – Tharkius Oct 27 '17 at 22:24
1

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

String result = String.join(", ", userSelectedSeats);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0
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()+ ",";
0

Replace the for loop with this,

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

Hope it helps!