2013-12-17 120 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