特殊外壳最后一个元素的最佳循环惯用语

发布于 2024-09-06 18:41:02 字数 1687 浏览 8 评论 0 原文

在进行简单的文本处理和打印语句时,我多次遇到这种情况,其中我循环遍历集合,并且我想对最后一个元素进行特殊处理(例如,除了最后一个情况之外,每个普通元素都将用逗号分隔)。

是否有一些最佳实践习惯用法或优雅的形式不需要重复代码或将 if, else 推入循环中。

例如,我有一个字符串列表,我想在逗号分隔的列表中打印这些字符串。 ( do while 解决方案已经假设列表有 2 个或更多元素,否则它会与更正确的条件循环一样糟糕)。

例如 List = ("dog", "cat", "bat")

我想打印 "[dog, cat, bat]"

我提出了 2 种方法

  1. 带条件的 For 循环

    public static String forLoopConditional(String[] items) {
    
    字符串 itemOutput = "[";
    
    for (int i = 0; i < items.length; i++) {
        // 检查我们是否不在最后一个元素
        if (i < (items.length - 1)) {
            itemOutput += items[i] + ", ";
        } 别的 {
            // 最后一个元素
            itemOutput += items[i];
        }
    }
    itemOutput += "]";
    
    返回项目输出;
     }
    
  2. do while 循环启动循环

    public static String doWhileLoopPrime(String[] items) {
    字符串 itemOutput = "[";
    整数 i = 0;
    
    itemOutput += items[i++];
    if (i < (items.length)) {
        做 {
            itemOutput += ", " + items[i++];
        while (i < items.length);
    }
    itemOutput += "]";
    
    返回项目输出;
    }
    

    测试人员类别:

    public static void main(String[] args) {
        String[] items = { "狗", "猫", "蝙蝠" };
    
        System.out.println(forLoopConditional(items));
        System.out.println(doWhileLoopPrime(items));
    
    }
    

在 Java AbstractCollection 类中,它具有以下实现(有点冗长,因为它包含所有边缘情况错误检查,但还不错)。

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(", ");
}
}

I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (for example every normal element will be comma separated except for the last case).

Is there some best practice idiom or elegant form that doesn't require duplicating code or shoving in an if, else in the loop.

For example I have a list of strings that I want to print in a comma separated list. (the do while solution already assumes the list has 2 or more elements otherwise it'd be just as bad as the more correct for loop with conditional).

e.g. List = ("dog", "cat", "bat")

I want to print "[dog, cat, bat]"

I present 2 methods the

  1. For loop with conditional

    public static String forLoopConditional(String[] items) {
    
    String itemOutput = "[";
    
    for (int i = 0; i < items.length; i++) {
        // Check if we're not at the last element
        if (i < (items.length - 1)) {
            itemOutput += items[i] + ", ";
        } else {
            // last element
            itemOutput += items[i];
        }
    }
    itemOutput += "]";
    
    return itemOutput;
     }
    
  2. do while loop priming the loop

    public static String doWhileLoopPrime(String[] items) {
    String itemOutput = "[";
    int i = 0;
    
    itemOutput += items[i++];
    if (i < (items.length)) {
        do {
            itemOutput += ", " + items[i++];
        } while (i < items.length);
    }
    itemOutput += "]";
    
    return itemOutput;
    }
    

    Tester class:

    public static void main(String[] args) {
        String[] items = { "dog", "cat", "bat" };
    
        System.out.println(forLoopConditional(items));
        System.out.println(doWhileLoopPrime(items));
    
    }
    

In the Java AbstractCollection class it has the following implementation (a little verbose because it contains all edge case error checking, but not bad).

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(", ");
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

眼泪淡了忧伤 2024-09-13 18:41:02

我通常这样写:

static String commaSeparated(String[] items) {
    StringBuilder sb = new StringBuilder();
    String sep = "";
    for (String item: items) {
        sb.append(sep);
        sb.append(item);
        sep = ",";
    }
    return sb.toString();
}

I usually write it like this:

static String commaSeparated(String[] items) {
    StringBuilder sb = new StringBuilder();
    String sep = "";
    for (String item: items) {
        sb.append(sep);
        sb.append(item);
        sep = ",";
    }
    return sb.toString();
}
原来是傀儡 2024-09-13 18:41:02

这些答案中有很多 for 循环,但我发现迭代器和 while 循环读取起来更容易。例如:

Iterator<String> itemIterator = Arrays.asList(items).iterator();
if (itemIterator.hasNext()) {
  // special-case first item.  in this case, no comma
  while (itemIterator.hasNext()) {
    // process the rest
  }
}

这是 Joiner 在 Google 集合中,我发现它非常可读。

There are a lot of for loops in these answers, but I find that an Iterator and while loop reads much more easily. E.g.:

Iterator<String> itemIterator = Arrays.asList(items).iterator();
if (itemIterator.hasNext()) {
  // special-case first item.  in this case, no comma
  while (itemIterator.hasNext()) {
    // process the rest
  }
}

This is the approach taken by Joiner in Google collections and I find it very readable.

俏︾媚 2024-09-13 18:41:02
string value = "[" + StringUtils.join( items, ',' ) + "]";
string value = "[" + StringUtils.join( items, ',' ) + "]";
雨的味道风的声音 2024-09-13 18:41:02

我通常的做法是测试索引变量是否为零,例如:

var result = "[ ";
for (var i = 0; i < list.length; ++i) {
    if (i != 0) result += ", ";
    result += list[i];
}
result += " ]";

但是,当然,只有当我们谈论没有某些 Array.join(", ") 方法的语言时才会这样。 ;-)

My usual take is to test if the index variable is zero, e.g.:

var result = "[ ";
for (var i = 0; i < list.length; ++i) {
    if (i != 0) result += ", ";
    result += list[i];
}
result += " ]";

But of course, that's only if we talk about languages that don't have some Array.join(", ") method. ;-)

凉墨 2024-09-13 18:41:02

我认为将第一个元素视为特殊情况更容易,因为更容易知道迭代是否是第一个而不是最后一个。不需要任何复杂或昂贵的逻辑就可以知道某件事是否是第一次进行。

public static String prettyPrint(String[] items) {
    String itemOutput = "[";
    boolean first = true;

    for (int i = 0; i < items.length; i++) {
        if (!first) {
            itemOutput += ", ";
        }

        itemOutput += items[i];
        first = false;
    }

    itemOutput += "]";
    return itemOutput;
}

I think it is easier to think of the first element as the special case because it is much easier to know if an iteration is the first rather than the last. It does not take any complex or expensive logic to know if something is being done for the first time.

public static String prettyPrint(String[] items) {
    String itemOutput = "[";
    boolean first = true;

    for (int i = 0; i < items.length; i++) {
        if (!first) {
            itemOutput += ", ";
        }

        itemOutput += items[i];
        first = false;
    }

    itemOutput += "]";
    return itemOutput;
}
一绘本一梦想 2024-09-13 18:41:02

我会用你的第二个例子,即。处理循环外的特殊情况,写得更简单一点:

String itemOutput = "[";

if (items.length > 0) {
    itemOutput += items[0];

    for (int i = 1; i < items.length; i++) {
        itemOutput += ", " + items[i];
    }
}

itemOutput += "]";

I'd go with your second example, ie. handle the special case outside of the loop, just write it a bit more straightforward:

String itemOutput = "[";

if (items.length > 0) {
    itemOutput += items[0];

    for (int i = 1; i < items.length; i++) {
        itemOutput += ", " + items[i];
    }
}

itemOutput += "]";
柠檬心 2024-09-13 18:41:02

Java 8 解决方案,以防有人正在寻找它:

String res = Arrays.stream(items).reduce((t, u) -> t + "," + u).get();

Java 8 solution, in case someone is looking for it:

String res = Arrays.stream(items).reduce((t, u) -> t + "," + u).get();
弄潮 2024-09-13 18:41:02

我喜欢对第一项使用标志。

 ArrayList<String> list = new ArrayList()<String>{{
       add("dog");
       add("cat");
       add("bat");
    }};
    String output = "[";
    boolean first = true;
    for(String word: list){
      if(!first) output += ", ";
      output+= word;
      first = false;
    }
    output += "]";

I like to use a flag for the first item.

 ArrayList<String> list = new ArrayList()<String>{{
       add("dog");
       add("cat");
       add("bat");
    }};
    String output = "[";
    boolean first = true;
    for(String word: list){
      if(!first) output += ", ";
      output+= word;
      first = false;
    }
    output += "]";
葬シ愛 2024-09-13 18:41:02

由于您的情况只是处理文本,因此您不需要循环内的条件。 AC 示例:

char* items[] = {"dog", "cat", "bat"};
char* output[STRING_LENGTH] = {0};
char* pStr = &output[1];
int   i;

output[0] = '[';
for (i=0; i < (sizeof(items) / sizeof(char*)); ++i) {
    sprintf(pStr,"%s,",items[i]);
    pStr = &output[0] + strlen(output);
}
output[strlen(output)-1] = ']';

不要添加条件以避免生成尾随逗号,而是继续生成它(以保持循环简单且无条件)并在末尾简单地覆盖它。很多时候,我发现像任何其他循环迭代一样生成特殊情况,然后在最后手动替换它会更清楚(尽管如果“替换它”代码超过几行,这种方法实际上会变得更难读)。

Since your case is simply processing text, you don't need the conditional inside the loop. A C example:

char* items[] = {"dog", "cat", "bat"};
char* output[STRING_LENGTH] = {0};
char* pStr = &output[1];
int   i;

output[0] = '[';
for (i=0; i < (sizeof(items) / sizeof(char*)); ++i) {
    sprintf(pStr,"%s,",items[i]);
    pStr = &output[0] + strlen(output);
}
output[strlen(output)-1] = ']';

Instead of adding a conditional to avoid generating the trailing comma, go ahead and generate it (to keep your loop simple and conditional-free) and simply overwrite it at the end. Many times, I find it clearer to generate the special case just like any other loop iteration and then manually replace it at the end (although if the "replace it" code is more than a couple of lines, this method can actually become harder to read).

清欢 2024-09-13 18:41:02

...

String[] items = { "dog", "cat", "bat" };
String res = "[";

for (String s : items) {
   res += (res.length == 1 ? "" : ", ") + s;
}
res += "]";

左右是相当可读的。当然,您可以将条件放在单独的 if 子句中。它的惯用之处(至少我认为是这样)是它使用 foreach 循环并且不使用复杂的循环头。

此外,没有重复的逻辑(即,只有一个地方将 items 中的项目实际附加到输出字符串 - 在现实世界的应用程序中,这可能复杂而冗长的格式化操作,所以我不想重复代码)。

...

String[] items = { "dog", "cat", "bat" };
String res = "[";

for (String s : items) {
   res += (res.length == 1 ? "" : ", ") + s;
}
res += "]";

or so is quite readable. You can put the conditional in a separate if clause, of course. What it makes idiomatic (I think so, at least) is that it uses a foreach loop and does not use a complicated loop header.

Also, no logic is duplicated (i.e. there is only one place where an item from items is actually appended to the output string - in a real world application this might be a more complicated and lengthy formatting operation, so I wouldn't want to repeat the code).

萌面超妹 2024-09-13 18:41:02

在这种情况下,您实质上是使用某些分隔符字符串连接字符串列表。你也许可以自己写一些东西来做到这一点。然后你会得到类似的结果:

String[] items = { "dog", "cat", "bat" };
String result = "[" + joinListOfStrings(items, ", ") + "]"

如果

public static String joinListOfStrings(String[] items, String sep) {
    StringBuffer result;
    for (int i=0; i<items.length; i++) {
        result.append(items[i]);
        if (i < items.length-1) buffer.append(sep);
    }
    return result.toString();
}

你有一个 Collection 而不是 String[] 你也可以使用迭代器和 hasNext()方法来检查这是否是最后一个。

In this case, you are essentially concatenating a list of strings using some separator string. You can maybe write something yourself which does this. Then you will get something like:

String[] items = { "dog", "cat", "bat" };
String result = "[" + joinListOfStrings(items, ", ") + "]"

with

public static String joinListOfStrings(String[] items, String sep) {
    StringBuffer result;
    for (int i=0; i<items.length; i++) {
        result.append(items[i]);
        if (i < items.length-1) buffer.append(sep);
    }
    return result.toString();
}

If you have a Collection instead of a String[] you can also use iterators and the hasNext() method to check if this is the last or not.

南街九尾狐 2024-09-13 18:41:02

如果您像这样动态构建字符串,则不应使用 += 运算符。
StringBuilder 类对于重复的动态字符串连接效果更好。

public String commaSeparate(String[] items, String delim){
    StringBuilder bob = new StringBuilder();
    for(int i=0;i<items.length;i++){
        bob.append(items[i]);
        if(i+1<items.length){
           bob.append(delim);
        }
    }
    return bob.toString();
}

然后调用是这样的

String[] items = {"one","two","three"};
StringBuilder bob = new StringBuilder();
bob.append("[");
bob.append(commaSeperate(items,","));
bob.append("]");
System.out.print(bob.toString());

If you are building a string dynamically like that, you shouldn't be using the += operator.
The StringBuilder class works much better for repeated dynamic string concatenation.

public String commaSeparate(String[] items, String delim){
    StringBuilder bob = new StringBuilder();
    for(int i=0;i<items.length;i++){
        bob.append(items[i]);
        if(i+1<items.length){
           bob.append(delim);
        }
    }
    return bob.toString();
}

Then call is like this

String[] items = {"one","two","three"};
StringBuilder bob = new StringBuilder();
bob.append("[");
bob.append(commaSeperate(items,","));
bob.append("]");
System.out.print(bob.toString());
尬尬 2024-09-13 18:41:02

一般来说,我最喜欢的是多层出口。更改

for ( s1; exit-condition; s2 ) {
    doForAll();
    if ( !modified-exit-condition ) 
        doForAllButLast();
}

for ( s1;; s2 ) {
    doForAll();
if ( modified-exit-condition ) break;
    doForAllButLast();
}

It 消除了任何重复代码或冗余检查。

你的例子:

for (int i = 0;; i++) {
    itemOutput.append(items[i]);
if ( i == items.length - 1) break;
    itemOutput.append(", ");
}

它在某些方面比其他方面更有效。对于这个具体的例子,我不太喜欢这个。

当然,对于退出条件取决于 doForAll() 中发生的情况而不仅仅是 s2 的情况,情况会变得非常棘手。使用Iterator就是这样的情况。

这是一篇论文 来自无耻地向他的学生推广它的教授:-)。请阅读第 5 节,了解您所讨论的内容。

Generally, my favourite is the multi-level exit. Change

for ( s1; exit-condition; s2 ) {
    doForAll();
    if ( !modified-exit-condition ) 
        doForAllButLast();
}

to

for ( s1;; s2 ) {
    doForAll();
if ( modified-exit-condition ) break;
    doForAllButLast();
}

It eliminates any duplicate code or redundant checks.

Your example:

for (int i = 0;; i++) {
    itemOutput.append(items[i]);
if ( i == items.length - 1) break;
    itemOutput.append(", ");
}

It works for some things better than others. I'm not a huge fan of this for this specific example.

Of course, it gets really tricky for scenarios where the exit condition depends on what happens in doForAll() and not just s2. Using an Iterator is such a case.

Here's a paper from the prof that shamelessly promoted it to his students :-). Read section 5 for exactly what you're talking about.

青柠芒果 2024-09-13 18:41:02

我认为这个问题有两个答案:任何语言中解决这个问题的最佳习惯用法,以及java中解决这个问题的最佳习惯用法。我还认为这个问题的目的不是将字符串连接在一起的任务,而是一般的模式,所以它并没有真正帮助显示可以做到这一点的库函数。

首先,用 [] 包围字符串和创建用逗号分隔的字符串的操作是两个单独的操作,并且理想情况下是两个单独的函数。

对于任何语言,我认为递归和模式匹配的组合效果最好。例如,在haskell中我会这样做:

join [] = ""
join [x] = x
join (x:xs) = concat [x, ",", join xs]

surround before after str = concat [before, str, after]

yourFunc = surround "[" "]" . join

-- example usage: yourFunc ["dog", "cat"] will output "[dog,cat]"

这样写的好处是它清楚地列举了函数将面临的不同情况,以及它将如何处理。

另一种非常好的方法是使用累加器类型函数。例如:

join [] = ""
join strings = foldr1 (\a b -> concat [a, ",", b]) strings 

这也可以用其他语言完成,例如 c#:

public static string Join(List<string> strings)
{
    if (!strings.Any()) return string.Empty;
    return strings.Aggregate((acc, val) => acc + "," + val);
}

在这种情况下效率不是很高,但在其他情况下可能很有用(或者效率可能并不重要)。

不幸的是,java 不能使用这两种方法。因此,在这种情况下,我认为最好的方法是在函数顶部检查异常情况(0 或 1 个元素),然后使用 for 循环来处理超过 1 个元素的情况:

public static String join(String[] items) {
    if (items.length == 0) return "";
    if (items.length == 1) return items[0];

    StringBuilder result = new StringBuilder();
    for(int i = 0; i < items.length - 1; i++) {
        result.append(items[i]);
        result.append(",");
    }
    result.append(items[items.length - 1]);
    return result.toString();
}

该函数清楚地表明两种边缘情况(0 或 1 个元素)中会发生什么。然后,它对除最后一个元素之外的所有元素使用循环,最后添加最后一个元素而不使用逗号。在开头处理非逗号元素的相反方法也很容易做到。

请注意, if (items.length == 1) return items[0]; 行实际上并不是必需的,但我认为它使函数的作用更容易一目了然。

(请注意,如果有人想要有关 haskell/c# 函数的更多解释,请询问,我会将其添加进去)

I think there are two answers to this question: the best idiom for this problem in any language, and the best idiom for this problem in java. I also think the intent of this problem wasn't the tasks of joining strings together, but the pattern in general, so it doesn't really help to show library functions that can do that.

Firstly though the actions of surrounding a string with [] and creating a string separated by commas are two separate actions, and ideally would be two separate functions.

For any language, I think the combination of recursion and pattern matching works best. For example, in haskell I would do this:

join [] = ""
join [x] = x
join (x:xs) = concat [x, ",", join xs]

surround before after str = concat [before, str, after]

yourFunc = surround "[" "]" . join

-- example usage: yourFunc ["dog", "cat"] will output "[dog,cat]"

The benefit of writing it like this is it clearly enumerates the different situations that the function will face, and how it will handle it.

Another very nice way to do this is with an accumulator type function. Eg:

join [] = ""
join strings = foldr1 (\a b -> concat [a, ",", b]) strings 

This can be done in other languages as well, eg c#:

public static string Join(List<string> strings)
{
    if (!strings.Any()) return string.Empty;
    return strings.Aggregate((acc, val) => acc + "," + val);
}

Not very efficient in this situation, but can be useful in other cases (or efficiency may not matter).

Unfortunately, java can't use either of those methods. So in this case I think the best way is to have checks at the top of the function for the exception cases (0 or 1 elements), and then use a for loop to handle the case with more than 1 element:

public static String join(String[] items) {
    if (items.length == 0) return "";
    if (items.length == 1) return items[0];

    StringBuilder result = new StringBuilder();
    for(int i = 0; i < items.length - 1; i++) {
        result.append(items[i]);
        result.append(",");
    }
    result.append(items[items.length - 1]);
    return result.toString();
}

This function clearly shows what happens in the two edge cases (0 or 1 elements). It then uses a loop for all but the last elements, and finally adds the last element on without a comma. The inverse way of handling the non-comma element at the start is also easy to do.

Note that the if (items.length == 1) return items[0]; line isn't actually necessary, however I think it makes what the function does more easier to determine at a glance.

(Note that if anyone wants more explanation on the haskell/c# functions ask and I'll add it in)

凉墨 2024-09-13 18:41:02

它可以使用 Java 8 lambda 和 Collectors.joining() 来实现 -

List<String> items = Arrays.asList("dog", "cat", "bat");
String result = items.stream().collect(Collectors.joining(", ", "[", "]"));
System.out.println(result);

It can be achieved using Java 8 lambda and Collectors.joining() as -

List<String> items = Arrays.asList("dog", "cat", "bat");
String result = items.stream().collect(Collectors.joining(", ", "[", "]"));
System.out.println(result);
椵侞 2024-09-13 18:41:02

我通常会写这样的for循环:

public static String forLoopConditional(String[] items) {
    StringBuilder builder = new StringBuilder();         

    builder.append("[");                                 

    for (int i = 0; i < items.length - 1; i++) {         
        builder.append(items[i] + ", ");                 
    }                                                    

    if (items.length > 0) {                              
        builder.append(items[items.length - 1]);         
    }                                                    

    builder.append("]");                                 

    return builder.toString();                           
}       

I usually write a for loop like this:

public static String forLoopConditional(String[] items) {
    StringBuilder builder = new StringBuilder();         

    builder.append("[");                                 

    for (int i = 0; i < items.length - 1; i++) {         
        builder.append(items[i] + ", ");                 
    }                                                    

    if (items.length > 0) {                              
        builder.append(items[items.length - 1]);         
    }                                                    

    builder.append("]");                                 

    return builder.toString();                           
}       
嘿嘿嘿 2024-09-13 18:41:02

如果您只是在寻找像这样的逗号分隔列表:“[The, Cat, in, the, Hat]”,甚至不要浪费时间编写自己的方法。只需使用 List.toString:

List<String> strings = Arrays.asList("The", "Cat", "in", "the", "Hat);

System.out.println(strings.toString());

假设 List 的泛型类型有一个带有您想要显示的值的 toString,只需调用 List.toString:

public class Dog {
    private String name;

    public Dog(String name){
         this.name = name;
    }

    public String toString(){
        return name;
    }
}

然后您可以执行以下操作:

List<Dog> dogs = Arrays.asList(new Dog("Frank"), new Dog("Hal"));
System.out.println(dogs);

您将得到:
[弗兰克,哈尔]

If you are just looking for a comma seperated list of like this: "[The, Cat, in, the, Hat]", don't even waste time writing your own method. Just use List.toString:

List<String> strings = Arrays.asList("The", "Cat", "in", "the", "Hat);

System.out.println(strings.toString());

Provided the generic type of the List has a toString with the value you want to display, just call List.toString:

public class Dog {
    private String name;

    public Dog(String name){
         this.name = name;
    }

    public String toString(){
        return name;
    }
}

Then you can do:

List<Dog> dogs = Arrays.asList(new Dog("Frank"), new Dog("Hal"));
System.out.println(dogs);

And you'll get:
[Frank, Hal]

探春 2024-09-13 18:41:02

第三种选择如下,

StringBuilder output = new StringBuilder();
for (int i = 0; i < items.length - 1; i++) {
    output.append(items[i]);
    output.append(",");
}
if (items.length > 0) output.append(items[items.length - 1]);

但最好是使用类似 join() 的方法。对于Java,有一个 String.join 在第三方库中,这样你的代码就变成:

StringUtils.join(items,',');

FWIW,join() 方法(第 3232 行起)确实使用循环内的 if :

public static String join(Object[] array, char separator, int startIndex, int endIndex)     {
        if (array == null) {
            return null;
        }
        int bufSize = (endIndex - startIndex);
        if (bufSize <= 0) {
            return EMPTY;
        }

        bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
        StringBuilder buf = new StringBuilder(bufSize);

        for (int i = startIndex; i < endIndex; i++) {
            if (i > startIndex) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

A third alternative is the following

StringBuilder output = new StringBuilder();
for (int i = 0; i < items.length - 1; i++) {
    output.append(items[i]);
    output.append(",");
}
if (items.length > 0) output.append(items[items.length - 1]);

But the best is to use a join()-like method. For Java there's a String.join in third party libraries, that way your code becomes:

StringUtils.join(items,',');

FWIW, the join() method (line 3232 onwards) in Apache Commons does use an if within a loop though:

public static String join(Object[] array, char separator, int startIndex, int endIndex)     {
        if (array == null) {
            return null;
        }
        int bufSize = (endIndex - startIndex);
        if (bufSize <= 0) {
            return EMPTY;
        }

        bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
        StringBuilder buf = new StringBuilder(bufSize);

        for (int i = startIndex; i < endIndex; i++) {
            if (i > startIndex) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文