Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder remove comma at the end of Last record [duplicate]

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();
like image 533
Sun Avatar asked Aug 20 '15 11:08

Sun


1 Answers

Java 8 Solution

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()));
like image 94
Fred Porciúncula Avatar answered Sep 16 '22 16:09

Fred Porciúncula