2013-12-17 123 views
2

我是java的初學者。在我的代碼中我有一個arraylist,我想完全輸出爲一個字符串。爲此我寫了這段代碼。如何將arraylist轉換爲字符串?

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); 
    } 

} 

和我的輸出是

hello first second third fourth 

我不想在最後一個元素之後的最後一個\噸。我怎麼能做到這一點。

+0

https://code.google.com/p/guava-libraries/wiki/StringsExplained查看此內容。 – Nishant

+0

類似問題:http://stackoverflow.com/questions/599161/best-way-to-convert-an-arraylist-to-a-string和http://stackoverflow.com/questions/1751844/java-convert- liststring-to-a-joind-string – user2314737

回答

5

一種解決方案是不使用的for-each循環,你可以做到以下幾點:

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

我建議你使用StringBuilder而不是+

其他的解決方案:

  • 修剪您完成構建後的字符串。
  • 使用Joiner
  • ...
+2

在最後一行中,'i'是否超出範圍? –

+0

@tobias_k謝謝:) – Maroun

+2

最好不要連接循環中的字符串。你可以使用一個StringBuilder ... –

2

如果是爲了調試,爲什麼不使用:

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

因爲他想在每個字符串之間加上'\ t'。 – Maroun

+1

他呢?他沒有提到有關格式的任何信息。爲什麼我說「如果是爲了調試」。當他只需要它來調試循環/修整/等將是矯枉過正的...... –

3

你有2個解決方案:

  • 使用明確的迭代器。
  • 使用番石榴Joiner(外部庫,您將需要導入它)。

迭代

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

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

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

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

提示:你也應該考慮使用,而不是字符串+ =

+0

爲您的第一個解決方案:最好不要連接循環中的字符串。你可以使用一個StringBuilder ... –

+0

我在答案的末尾添加了它作爲提示。 –

3

使用TR一個StringBuilder IM()。

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

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

爲什麼添加一些東西以後被刪除? –

0

因爲你有一個尾隨\t個字符數,你會希望在打印前行刪除最後一個字符。看到這個代碼示例:

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

所以,上面插入您的System.out.println(listString)語句來這一權利。

1

來自apache commons(http://commons.apache.org/proper/commons-lang/)。下載並用作外部jar庫。

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

這是標準庫的一部分嗎?如果不是,它從哪裏來? –

+0

它來自apache.commons。 http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html並且工作良好 – MaVRoSCy

0

您可以使用此:

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

     else 
     listString += s; 

     index++; 
    } 

只有在最後一次迭代也不會添加標籤空間。

1

使用修整()方法:

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

使用StringUtils.join()方法。

0

用途:

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

而不是使用String類使用StringBuilder對象以節省內存也。 例子:

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)); 
2

您可以使用 「調試」

myList.toString(); 

您可以使用您提供一些編輯只

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

裝飾相同的代碼()將無法正常工作...

2

有很多方法可以解決這個問題!我通常會去平常的for loop with an index,只需將尾隨字符添加到n-1的位置即可。但是今天我決定進行一些快速測試,看看哪種方法更快,以下是我的結果:

(另外,我假設 - 相信 - StrinBuffer .append()的分期時間爲O(1))

使用

方法:對於循環,foreach循環和Iterator

1)循環

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) 
} 

對於一兩件事,我才意識到,我可以加速這個循環起來通過將stringArray.size()-1調用保存到變量而不是調用它很多次(我的壞!)。除此之外,我認爲這個循環最糟糕的部分是stringArray.get(index),因爲所用代碼的其餘部分與StringBuffer有關,它也用於其他循環。 ()是不變的,因爲.get()是不變的時間,O(1)。

2)Foreach循環

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)同迭代

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) 
} 

可能的時間的問題? it.hasNext()的雙重提問。但是,可惜的是,在性能方面應該不是什麼大問題,因爲如果你看看ArrayList返回的Iterator的代碼hasNext(),你會發現它僅僅是一個比較,所以它將是O(1)次。

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

結論

所有的循環的結束有,理論上,O(n)的時間複雜度。它們會根據比較而略有不同,但不會太多。這意味着您可以選擇任何您喜歡的方式,而無需擔心性能問題,因此您可以選擇最適合您的代碼或最適合您的代碼。這不是很好嗎?

以下是一些快速測試的備份理論。

成績 以秒爲單位。

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:我不得不將測試結果放在一個「代碼塊」中,因爲某些樣式原因它們顯示在一行中? :S