Java 8 solution
You don't need validation when using Java 8. All you need to do is use StringJoiner (or String.join() ).
StringJoiner joiner = new StringJoiner(","); for (int i = 0; i < arrayList.size(); i++) { String name = arrayList.get(i).getName(); int price = arrayList.get(i).getPrice(); joiner.add(strName + " - " + price); } String joinedString = joiner.toString();
And you can make it even cleaner by using the Stream API (thanks to @Sasha):
String joinedString = String.join(",", list.stream().map( e -> e.getName() + " - " + e.getPrice()).collect(Collectors.toList()));
source share