Best Loop Idiom for special casing the last element

后端 未结 18 965
梦毁少年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 10:01

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

提交回复
热议问题