Logo

Programming-Idioms

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

Idiom #360 Create a formatted list

Create the end-user text, s, specifying the contents of collection a.

For example, "A", "A and B", "A, B, and C", etc.

import static java.lang.String.join;
import static java.util.Arrays.copyOfRange;
int n = a.length - 1;
String s = switch (n) {
    case 0 -> a[0];
    case 1 -> a[0] + " and " + a[1];
    default -> {
        s = join(", ", copyOfRange(a, 0, n));
        yield s + ", and " + a[n];
    }
};

New implementation...
< >
reilas