I am using StringBuilder to show comma between records, but also getting comma at the end of Last Record
How to control on this ? I don't like to see comma at the end of last record - because it's useless
for (int i = 0; i < arrayList.size(); i++) {
String name = arrayList.get(i).getName();
int price = arrayList.get(i).getPrice();
stringBuilder.append(strName);
stringBuilder.append(" - "+price+",");
}
stringFinal = stringBuilder.toString();
You don't need any check when using Java 8. All you need is to 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 taking advantage of the Stream
API (thanks to @Sasha):
String joinedString = String.join(",", list.stream().map(
e -> e.getName() + " - " + e.getPrice()).collect(Collectors.toList()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With