Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert arraylist into string?

Tags:

java

arraylist

I am beginner in java. In my code i have a arraylist and i want to output completely as a String. for this i have write this code.

package factorytest;

import java.util.ArrayList;
import java.util.List;

public class MatchingWord {

    public static void main(String[] args) {

        List <String> myList = new ArrayList<String>();
        myList.add("hello");
        myList.add("first");
        myList.add("second");
        myList.add("third");
        myList.add("fourth");

        // 1st approach
        String listString = "";

        for (String s : myList)
        {
            listString += s + "\t";
        }
System.out.println(listString);
    }

}

and my output is

hello   first   second  third   fourth  

i don't want the last \t after the last element. how can i achieve this.

like image 336
user2142786 Avatar asked Jun 07 '26 23:06

user2142786


1 Answers

One solution is not using for-each loop, you can do the following:

int i;
for(i = 0;i < myList.size() - 1;i++) {
    listString += myList.get(i) + "\t";
}
listString += myList.get(i);

I recommend you to use StringBuilder instead of +.

Other solutions:

  • Trimming the String after you finish constructing it.
  • Using Joiner.
  • ...
like image 113
Maroun Avatar answered Jun 10 '26 11:06

Maroun