用逗号分隔列表的最简单方法?
用Java逗号分隔列表的最清晰方法是什么?
What is the clearest way to comma-delimit a list in Java?
我知道几种方法,但是我想知道最好的方法是什么(最好"是指最清晰和/或最短而不是最有效的方法.
I know several ways of doing it, but I'm wondering what the best way is (where "best" means clearest and/or shortest, not the most efficient.
我有一个列表,我想遍历它,打印每个值.我想在每个项目之间打印一个逗号,但不要在最后一个项目之后(也不在第一个项目之前).
I have a list and I want to loop over it, printing each value. I want to print a comma between each item, but not after the last one (nor before the first one).
List --> Item ( , Item ) *
List --> ( Item , ) * Item
示例解决方案1:
boolean isFirst = true;
for (Item i : list) {
if (isFirst) {
System.out.print(i); // no comma
isFirst = false;
} else {
System.out.print(", "+i); // comma
}
}
示例解决方案2-创建一个子列表:
Sample solution 2 - create a sublist:
if (list.size()>0) {
System.out.print(list.get(0)); // no comma
List theRest = list.subList(1, list.size());
for (Item i : theRest) {
System.out.print(", "+i); // comma
}
}
示例解决方案3:
Iterator<Item> i = list.iterator();
if (i.hasNext()) {
System.out.print(i.next());
while (i.hasNext())
System.out.print(", "+i.next());
}
这些特别对待第一个项目;可以改而特别地对待最后一个.
These treat the first item specially; one could instead treat the last one specially.
顺便说一下,这是在Java 1.6中实现List
toString
的方法(它是从AbstractCollection
继承的):
Incidentally, here is how List
toString
is implemented (it's inherited from AbstractCollection
), in Java 1.6:
public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
它尽早退出循环以避免最后一项后面的逗号.顺便说一句:这是我第一次记得看到(本收藏集)";这是激发它的代码:
It exits the loop early to avoid the comma after the last item. BTW: this is the first time I recall seeing "(this Collection)"; here's code to provoke it:
List l = new LinkedList();
l.add(l);
System.out.println(l);
我欢迎任何解决方案,即使它们使用意外的库(regexp?);以及Java以外的其他语言的解决方案(例如,我认为Python/Ruby具有 intersperse 函数- 的实现方式是什么?).
I welcome any solution, even if they use unexpected libraries (regexp?); and also solutions in languages other than Java (e.g. I think Python/Ruby have an intersperse function - how is that implemented?).
澄清:通过库,我的意思是标准Java库.对于其他库,我认为它们可以与其他语言一起使用,并且想知道它们是如何实现的.
Clarification: by libraries, I mean the standard Java libraries. For other libraries, I consider them with other languages, and interested to know how they're implemented.
EDIT 工具箱提到了类似的问题:最后Java中增强的for循环的迭代
EDIT toolkit mentioned a similar question: Last iteration of enhanced for loop in java
还有另一个: 循环中的最后一个元素是否值得单独使用治疗?
Java 8及更高版本
使用 StringJoiner
类:
Java 8 and later
Using StringJoiner
class :
StringJoiner joiner = new StringJoiner(",");
for (Item item : list) {
joiner.add(item.toString());
}
return joiner.toString();
使用 Stream
,和 Collectors
:
return list.stream().
map(Object::toString).
collect(Collectors.joining(",")).toString();
Java 7和更早版本
另请参见#285523
String delim = "";
for (Item i : list) {
sb.append(delim).append(i);
delim = ",";
}