Java 基本字符串操作,删除While循环中的最后一个字符

Java 基本字符串操作,删除While循环中的最后一个字符,java,collections,Java,Collections,我正在努力处理下面的基本代码 如何防止最后一个逗号“,”附加到字符串中 String outScopeActiveRegionCode=""; List<String> activePersons=new ArrayList<String>(); HashSet<String> outScopeActiveRegionCodeSet=new HashSet<String>(); for (String pers

我正在努力处理下面的基本代码

如何防止最后一个逗号“,”附加到字符串中

    String outScopeActiveRegionCode="";

    List<String> activePersons=new ArrayList<String>();

    HashSet<String> outScopeActiveRegionCodeSet=new HashSet<String>();

    for (String person : activePersons) {

       outScopeActiveRegionCodeSet.add(person); 

    }
       Iterator itr = outScopeActiveRegionCodeSet.iterator();

             while(itr.hasNext()){
                outScopeActiveRegionCode+=itr.next();
                outScopeActiveRegionCode+=",";
             }
字符串outScopeActiveRegionCode=”“;
List activePersons=new ArrayList();
HashSet outScopeActiveRegionCodeSet=新HashSet();
for(字符串人员:活动人员){
OutScopeActiveRegionCode.add(人);
}
迭代器itr=outScopeActiveRegionCodeSet.Iterator();
while(itr.hasNext()){
outScopeActiveRegionCode+=itr.next();
outScopeActiveRegionCode+=“,”;
}

Id实际上是另一种方式,除了第一种情况,我会在所有情况下都加上逗号,这更简单

boolean isFirst = true;
while(itr.hasNext()) {
    if(isFirst) {
        isFirst = false;
    } else {
        outScopeActiveRegionCode+=",";
    }
    outScopeActiveRegionCode+=itr.next();
}
原因是检测第一个病例比检测最后一个病例要简单得多。

我会:

String delimiter = "";

while(itr.hasNext()){
    outScopeActiveRegionCode += delimiter;
    outScopeActiveRegionCode += itr.next();
    delimiter = ",";
}

也许你可以在使用StringBuilder而不是字符串附加commaConsider之前执行另一个hasNext()。我也喜欢这样,我不得不承认我不知道后台的效率有多高,但是,每次为分隔符变量赋值会比每次检查布尔变量以查看是否在第一个元素上花费更大吗?只是一个想法。我刚刚做了一些测试,似乎作业更快。当然,您只会在列表大小增加时注意到它。在大多数情况下,这无关紧要,因此两种解决方案都是好的。