Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #362 Create delimited list

From list a, create the text s specifying the contents of a, such that items are separated by delimiter d and items containing 1 or more spaces are quoted with quote character q.
Example: "A "," B"," C ",D,E,F

String s = a.stream()
    .map(x -> {
        if (!x.contains(" ")) return x;
        return q + x + q;
    })
    .reduce((x, y) -> x + d + y)
    .get();
import java.util.ArrayList;
import static java.lang.String.join;
class QuotedList extends ArrayList<String> {
    String d, q;
    QuotedList(String d, String q) {
        this.d = d;
        this.q = q;
    }
    public boolean add(String s) {
        if (s.contains(" ")) s = q + s + q;
        return super.add(s);
    }
    public String toString() {
        return join(d, this);
    }
}
QuotedList x = new QuotedList(d, q);
classes
  a.Delimiter := d;
  a.QuoteChar := q;
  a.StrictDelimiter := False;
  a.AlwaysQuote := False;
  s := a.DelimitedText;
s = a.map{_1.include?(" ") ? q + _1 + q : _1 }.join(d)

New implementation...
< >
Bart