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.
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:
Joiner.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With