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.

Chandrayya G K
  • 8,719
  • 5
  • 40
  • 68
user2142786
  • 1,484
  • 9
  • 41
  • 74
  • https://code.google.com/p/guava-libraries/wiki/StringsExplained look into this. – Nishant Dec 17 '13 at 09:33
  • Similar questions: http://stackoverflow.com/questions/599161/best-way-to-convert-an-arraylist-to-a-string and http://stackoverflow.com/questions/1751844/java-convert-liststring-to-a-joind-string – user2314737 Dec 17 '13 at 09:59

12 Answers12

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.
  • ...
Maroun
  • 94,125
  • 30
  • 188
  • 241
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+=

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
3

Use trim().

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

listString = listString.trim();
System.out.println(listString);
PakkuDon
  • 1,627
  • 4
  • 22
  • 21
2

If it is for debugging, why not use:

System.out.println(myList.toString());
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
  • Because he wants to add `\t` between each string. – Maroun Dec 17 '13 at 09:31
  • 1
    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... – R. Oosterholt Dec 17 '13 at 09:43
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...

Ahmed Hamdy
  • 2,547
  • 1
  • 17
  • 23
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

Chayemor
  • 3,577
  • 4
  • 31
  • 54
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'));
Reinstate Monica Please
  • 11,123
  • 3
  • 27
  • 48
  • Is this part of the standard library? If not, where is it from? – tobias_k Dec 17 '13 at 09:34
  • its from apache.commons . http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html and work well – MaVRoSCy Dec 17 '13 at 09:36
1

Use the trim() method :

System.out.print(listString.trim());
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.

andrel
  • 1,144
  • 11
  • 25
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.

SoulRayder
  • 5,072
  • 6
  • 47
  • 93
0

Use StringUtils.join() method.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
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));
Nishant Lakhara
  • 2,295
  • 4
  • 23
  • 46