Skip to content
Advertisement

In for each loop i want to skip “, ” in last iteration

I want to skip printing “, ” in last iteration.

I want output like name, name, name

Output now i am getting is name, name, name,

StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
    stringBuffer.append(cast.getName() + ", ");
}

Advertisement

Answer

You can append the comma before you append the name. Like this:

StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
    if (stringBuffer.length() != 0) {
        stringBuffer.append(",");
    }
    stringBuffer.append(cast.getName());
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement