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 (
I like to use a flag for the first item.
ArrayList list = new ArrayList(){{ add("dog"); add("cat"); add("bat"); }}; String output = "["; boolean first = true; for(String word: list){ if(!first) output += ", "; output+= word; first = false; } output += "]";