Best Loop Idiom for special casing the last element

后端 未结 18 983
梦毁少年i
梦毁少年i 2020-12-23 09:25

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 (

18条回答
  •  臣服心动
    2020-12-23 09:58

    ...

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

提交回复
热议问题