Java - Write code to convert List To String With Separator

Requirements

Write code to convert List To String With Separator

Demo

//package com.book2s;

import java.util.Iterator;
import java.util.List;

public class Main {
    public static String convertListToStringWithSeparator(
            List<String> myList, String separator) {
        StringBuilder result = new StringBuilder();

        Iterator<String> iter = myList.iterator();
        while (iter.hasNext()) {
            String item = iter.next();

            // append each list item to the result string
            result.append(item);//from   w w w  .  j  av a  2s.c  o  m

            // do this only if we have more
            if (iter.hasNext()) {
                result.append(separator);
            }
        }
        return result.toString();
    }
}

Related Topic