Skip to content

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() + ", ");
}

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());
}