2

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.

2

12 Answers 12

5

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.
  • ...
Sign up to request clarification or add additional context in comments.

5 Comments

Won't the i be out of scope in the last line?
@R.Oosterholt That's what I said :)
By using this we are not able to get the last element.
@user2142786 Why not?
now i got it u r adding the last element after for loop. i was skip that line. thanx :)
3

Use trim().

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

listString = listString.trim();
System.out.println(listString);

1 Comment

why add something to be removed later?
3

You have 2 solutions :

  • Use explicitly an iterator.
  • Use Guava Joiner (external lib, you will need to import it).

Iterator :

Iterator<String> it = myList.iterator();

while(it.hasNext()) {
   listString += it.next();

   if(it.hasNext()) {
     listString += "\t";
   }
}

Joiner :

Joiner j = Joiner.on("\t);
System.out.println(j.join(myList));

Hint : You should also consider using a StringBuilder instead of String+=

2 Comments

for your first solution: better not concatenate strings in a loop. You could use a StringBuilder...
I added it as a hint at the end of the answer.
2

If it is for debugging, why not use:

System.out.println(myList.toString());

2 Comments

Because he wants to add \t between each string.
does he? He didn't mention anything about the format. THats why I said "if it is for debugging". When he only needs it for debugging looping/trimming/etc would be overkill...
2

You can either use "Debugging"

myList.toString();

You can use the same code you provided with some edits only

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

trim() won't work...

Comments

2

There are so many ways to solve this! I have usually gone for the usual for loop with an index and just add the trailing character up until the n-1 position. But today I decided to run a couple of quick tests to see which method is faster, and here are my results:

(Also, I am assuming --believing-- that StrinBuffer .append() has an amortized time of O(1). )

Methods used: For loop, Foreach loop, and Iterator

1) For loop

private static String getStringWithForIndex(ArrayList<String> stringArray){
    StringBuffer buffer = new StringBuffer(); //O(1)
    int index;  //O(1)
    for(index=0; index<stringArray.size()-1; ++index){  //In all O(n)
        buffer.append(stringArray.get(index));
        buffer.append("\n");
    }   
    buffer.append(stringArray.get(index));  //O(1);

    return buffer.toString(); O(n)
}

For one thing I just realized, I could have sped this loop up by saving the stringArray.size()-1 call to a variable rather than have it called so many times (my bad!). Aside from that, I'd figure that the worst part of this loop is the stringArray.get(index) because the rest of the code used pertains to the StringBuffer, which is used in the other loops as well.

Nonetheless, it shouldn't be bad at all because .get() is constant time, O(1).

2) Foreach loop

private static String getStringWithForEach(ArrayList<String> stringArray){
    StringBuffer buffer = new StringBuffer();  //O(1)
    for(String word : stringArray){   // In all O(n)
        buffer.append(word);
        buffer.append("\n");
    }

    buffer.deleteCharAt(buffer.length()-1); 
    //O(1) because IT'S THE LAST CHARACTER ALWAYS

    return buffer.toString(); //O(n)
}

3) With Iterator

private static String getStringWithIterator(ArrayList<String> stringArray){ 
    Iterator it = stringArray.iterator(); //O(1)
    StringBuffer buffer = new StringBuffer(); //O(1)
    while(it.hasNext()){ //In all O(n)
        buffer.append(it.next());
        if(it.hasNext())
            buffer.append("\n");
    }

    return buffer.toString(); //O(n)
}

Possible time problem? The double questioning of it.hasNext(). But alas,it should not be much of a problem in terms of performance because if you look at the code involved in hasNext() for the Iterator returned by ArrayList you'll see it's a mere comparison, so it would be O(1) time.

public boolean hasNext() {
        return cursor != size; 
}

Conclusion

All of the loops end up having, theoretically, O(n) time complexity. They will vary very slightly depending on the comparisons made, but not by much. That means that you can choose whichever method you would like without worrying on performance, so you have the luxury to choose the code that reads the best or suits you the best. Isn't that great?

Here are a couple of quick tests to back up the theory.

RESULTS Measured in seconds.

test1 62.9kb

With Iterator: 0.003 
With Foreach: 0.007 
With ForIndex: 0.002


With Iterator: 0.008
With Foreach: 0.009
With ForIndex: 0.002


With Iterator: 0.004
With Foreach: 0.015
With ForIndex: 0.002

With Iterator: 0.007
With Foreach: 0.008
With ForIndex: 0.003

With Iterator: 0.003
With Foreach: 0.003
With ForIndex: 0.002

With Iterator: 0.006
With Foreach: 0.01
With ForIndex: 0.002

*Average* With Iterator: 0.006
*Average* With Foreach: 0.009
*Average* With ForIndex: 0.002

test2 6.4 mb

With Iterator: 0.102
With Foreach: 0.115
With ForIndex: 0.121

With Iterator: 0.104
With Foreach: 0.109
With ForIndex: 0.118

With Iterator: 0.106
With Foreach: 0.123
With ForIndex: 0.126

With Iterator: 0.099
With Foreach: 0.109
With ForIndex: 0.12

With Iterator: 0.098
With Foreach: 0.109
With ForIndex: 0.119

With Iterator: 0.1
With Foreach: 0.119
With ForIndex: 0.122

*Average* With Iterator: 0.102
*Average* With Foreach: 0.114
*Average* With ForIndex: 0.121

test3 47 mb

With Iterator: 0.116
With Foreach: 0.137
With ForIndex: 0.131

With Iterator: 0.118
With Foreach: 0.146
With ForIndex: 0.119

With Iterator: 0.115
With Foreach: 0.125
With ForIndex: 0.137

With Iterator: 0.11
With Foreach: 0.111
With ForIndex: 0.145

With Iterator: 0.096
With Foreach: 0.108
With ForIndex: 0.113

With Iterator: 0.096
With Foreach: 0.102
With ForIndex: 0.115

*Average* With Iterator: 0.108
*Average* With Foreach: 0.122
*Average* With ForIndex: 0.127

ps: I had to put the test results in a "code block" because for some styling reason they are showing in a single line? :S

Comments

1

Use the trim() method :

System.out.print(listString.trim());

Comments

1

From apache commons (http://commons.apache.org/proper/commons-lang/). Download and use as external jar lib.

System.out.println(StringUtils.join(myList, '\t'));

2 Comments

Is this part of the standard library? If not, where is it from?
0

Because you have a trailing \t-character, you will want to remove the last character before printing the line. See this code example:

if (!listString.isEmpty) {
    listString = listString.substring(0, str.length()-1);
}

So, insert this right above your System.out.println(listString)-statement.

Comments

0

Use StringUtils.join() method.

Comments

0

You can use this:

 int index = 0;
  for (String s : myList)
    {
         if(index!=(myList.size-1))
         listString += s + "\t";

         else
         listString += s;   

         index++; 
    }

Only in the last iteration it will not add the tab space.

Comments

0

Use :

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

Also instead of using String class use StringBuilder object to save memory. Example :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.