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

ash*_*thi 2 java collections

我正在努力使用下面的基本代码,

如何防止最后一个逗号","被附加到字符串.

    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+=",";
             }
Run Code Online (Sandbox Code Playgroud)

Jon*_*lor 6

我实际上是反过来做的,id除了第一个之外的所有情况之前都附加逗号,它更容易.

boolean isFirst = true;
while(itr.hasNext()) {
    if(isFirst) {
        isFirst = false;
    } else {
        outScopeActiveRegionCode+=",";
    }
    outScopeActiveRegionCode+=itr.next();
}
Run Code Online (Sandbox Code Playgroud)

这样做的原因是,检测第一种情况比最后一种情况简单得多.