Scott Mayers Scott Mayers - 4 months ago 18
Java Question

Join strings with different separators in Java

I have a list of strings, e.g. days of the week. And I'd like to join them on comma, with "and" before the last element. E.g: "I'm available on Tue, Wed, Thu and Fri".

Something elegant like

Joiner.on(", ").join(days)


Does not work. Is there an elegant way to do it with Guava or similar library?

Thanks

Answer

Java 6/7 compatible solution using Guava:

static String join(List<String> strings, String separator, String lastSeparator)
{
    checkNotNull(strings);
    switch (strings.size()) {
        case 0:
            return "";
        case 1:
            return strings.get(0);
        default:
            return Joiner.on(separator).join(strings.subList(0, strings.size() - 1))
                    + lastSeparator + strings.get(strings.size() - 1);
    }
}

or if you want to accept Iterable (and / or use more Guava stuff):

static String join(Iterable<String> strings, String separator, String lastSeparator)
{
    checkNotNull(strings);
    int size = Iterables.size(strings);
    switch (size) {
        case 0:
            return "";
        case 1:
            return strings.iterator().next();
        default:
            return Joiner.on(separator).join(Iterables.limit(strings, size - 1))
                    + lastSeparator + Iterables.getLast(strings);
    }
}

It handles all edge cases except null elements in strings - if you want to handle them and not throw NPE, add .useForNull(stringForNull) to your joiner.

Comments