通过 Java 中的 for-each 循环检测第一次迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10502503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting the first iteration through a for-each loop in Java
提问by user903724
I'm working on a server that returns character separated lists to its client. In order to build these lists I have to detect the first iteration through a for-each loop:
我正在一个服务器上工作,它将字符分隔的列表返回给它的客户端。为了构建这些列表,我必须通过 for-each 循环检测第一次迭代:
StringBuilder builder = new StringBuilder() ;
boolean firstIterationFlag = true ;
for ( String s : list ){
if ( firstIterationFlag) {
firstIterationFlag = false ;
} else {
builder.append(separator);
}
builder.append(s) ;
}
return builder.toString() ;
Is there a way of doing this without the flag?
有没有办法在没有标志的情况下做到这一点?
采纳答案by Jon Skeet
One simpler way for this situation is to note that you can always append an empty string:
这种情况的一种更简单的方法是注意您始终可以附加一个空字符串:
// For the first iteration, use a no-op separator
String currentSeparator = "";
for (String s : list) {
builder.append(currentSeparator);
builder.append(s);
// From the second iteration onwards, use this
currentSeparator = separator;
}
Alternatively (and preferrably) use Guava's Joiner
class to start with :)
或者(最好)使用 Guava 的Joiner
类开始:)
This "joiner" scenario is almost alwaysthe one given for this requirement - so just use Joiner
. For other scenarios, either use a regular for
loop or use the condition as per your code.
这种“加入者”场景几乎总是针对此要求给出的场景- 所以只需使用Joiner
. 对于其他场景,请使用常规for
循环或根据您的代码使用条件。
回答by Sean Patrick Floyd
Not using foreach, but by using the iterator manually:
不使用 foreach,而是手动使用迭代器:
Iterator<String> it = list.iterator();
if(it.hasNext()){
doSomeThingForTheFirstTime(it.next());
while(it.hasNext()){
doSomethingElse(it.next);
}
}
(btw, this is pretty much what Guava's Joiner class does internally, though on a higher level)
(顺便说一句,这几乎是 Guava 的 Joiner 类在内部所做的,尽管在更高的层次上)
回答by andersoj
In the specific case you cite, use Guava's Joinerinstead of rolling your own...
在您引用的特定情况下,请使用 Guava 的Joiner而不是滚动您自己的...
An object which joins pieces of text (specified as an array, Iterable, varargs or even a Map) with a separator. It either appends the results to an Appendable or returns them as a String. Example:
用分隔符连接文本片段(指定为数组、Iterable、可变参数甚至是 Map)的对象。它将结果附加到 Appendable 或将它们作为字符串返回。例子:
Joiner joiner = Joiner.on(separator).skipNulls();
return joiner.join(list);
回答by amoebe
Java 8 Solution
Java 8 解决方案
If you have Java 8 available, you can simply use String#join
, no need for Guava:
如果你有 Java 8,你可以简单地使用String#join
,不需要 Guava:
String.join(", ", list)
回答by u2603230
You can try this :)
你可以试试这个:)
int i = 0;
for (something : manythings) {
i++;
}
回答by Krrose27
Just for the fun here is a different option.
只是为了好玩,这里有一个不同的选择。
StringBuilder builder = new StringBuilder();
for (String s : list) {
builder.append(separator);
builder.append(s);
}
builder.deleteCharAt(0);
return builder.toString();
回答by Peter
Well, this will not detect the first iteration in the loop, but solve the problem. Just append the seperator at the end of each string and cut off the last seperator.
好吧,这不会检测循环中的第一次迭代,而是解决问题。只需在每个字符串的末尾附加分隔符并切断最后一个分隔符。
StringBuilder builder = new StringBuilder() ;
for ( String s : list ) {
builder.append(s) ;
builder.append(separator);
}
builder.setLength(builder.length() - separator.length());
return builder.toString() ;
回答by Pierre
I would use commons.lang StringUtils.join function (see http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringUtils.html). I strongly recommend that you get acquainted with this and other helper libraries to avoid re-inventing the wheel.
我会使用 commons.lang StringUtils.join 函数(参见http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringUtils.html)。我强烈建议您熟悉这个和其他帮助程序库,以避免重新发明轮子。
回答by Paul Vargas
You could also use the following method:
您还可以使用以下方法:
public static String toString(List<?> list, String separator) {
StringBuilder sb = new StringBuilder();
Iterator<?> it = list.iterator();
while (it.hasNext()) {
Object next = it.next();
sb.append(next);
if (it.hasNext()) {
sb.append(separator);
}
}
return sb.toString();
}
The enhanced for
statement is equivalent to a basic for
statement of the form:
增强for
语句等效于for
以下形式的基本语句:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt TargetType Identifier =
(TargetType) #i.next();
Statement
}
#i
is an automatically generated identifier
#i
是一个自动生成的标识符