English 中文(简体)
是否有一种实用的方法,通过具体描述将清单分开?
原标题:Is there a utility method to separate a list by given string?

在<代码>中是否有这样的东西。 * E/CN.6/2009/1。 页: 1 使用这种方法?

List<String> list = new ArrayList<String>();
list.add("moo");
list.add("foo");
list.add("bar");

String enumeratedList = Util.enumerate(list, ", ");

assert enumeratedList == "moo, foo, bar";

我记得在php中使用<代码>implode,这是对java的搜查。

$array = array( lastname ,  email ,  phone );
$comma_separated = implode(",", $array);
最佳回答

你可以像下面这样使用StringUtils.join(Object[] array, String delimiter)(来自commons-lang):

String enumeratedList = StringUtils.join(list.toArray(), ", ");
问题回答

如果您不想依赖commons-lang,那么实现起来相当容易。将List转换为Array再将其合并成字符串并不理想。相反,只需遍历您的集合即可。甚至比使用Collection更好的是使用Iterable,它可以处理可迭代的任何内容(甚至是某些未知长度的流或Collection)。

import java.util.Arrays;
import java.util.Iterator;

public class JoinDemo {
  public static String join(String sep, Iterable<String> i) {
    StringBuilder sb = new StringBuilder();
    for (Iterator<String> it = i.iterator(); it.hasNext();) {
      sb.append(it.next());
      if (it.hasNext())
        sb.append(sep);
    }
    return sb.toString();
  }

  public static void main(String[] args) {
    System.out.println(join(",", Arrays.asList(args)));
  }
}

例:

# javac JoinDemo.java
# java JoinDemo a b c
a,b,c




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签