通过Java中的for-each循环检测第一次迭代 [英] Detecting the first iteration through a for-each loop in Java

查看:152
本文介绍了通过Java中的for-each循环检测第一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个服务器,它将字符分隔的列表返回给客户端。
为了构建这些列表,我必须通过一个for-each循环来检测第一个迭代:
$ b $ pre $ String $ builder builder = new StringBuilder();
boolean firstIterationFlag = true;

(String s:list){
if(firstIterationFlag){
firstIterationFlag = false;
} else {
builder.append(separator);
}
builder.append(s);
}
return builder.toString();

有没有这样做的方式没有国旗?

$ b $

  //对于第一次迭代,使用无操作分隔符
String currentSeparator =;
for(String s:list){
builder.append(currentSeparator);
builder.append(s);
//从第二次迭代开始,使用
currentSeparator = separator;

$ / code>

或者(最好是)使用Guava的 Joiner 类开始:)

这个joiner场景几乎总是 给出的这个需求 - 所以只需使用。对于其他场景,请使用常规的 for 循环或根据您的代码使用条件。


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:

    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?

解决方案

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

This "joiner" scenario is almost always the 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.

这篇关于通过Java中的for-each循环检测第一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆