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 (
It can be achieved using Java 8 lambda and Collectors.joining() as -
List items = Arrays.asList("dog", "cat", "bat"); String result = items.stream().collect(Collectors.joining(", ", "[", "]")); System.out.println(result);