Class ListPhrase


  • public final class ListPhrase
    extends Object
    Formats a list in a size-dependent way. List separators define how to separate two elements of the list. You can define 3 different separators:
    • separator for lists with exactly 2 elements (e.g. "first and second")
    • for lists with more than 2 elements, the separator for all but the last element (e.g. "first, second, …")
    • for lists with more than 2 elements, the separator for the second-last and last element (e.g. "second-last, and last")
    The join methods will throw exceptions if the list is null, or contains null or empty ("") elements. They will also throw if ListPhrase.Formatter.format(Object) returns null or an empty string.

    E.g.

      // Use the same separator for lists of all sizes.
      ListPhrase list = ListPhrase.from(", ");
      list.join(Arrays.asList("one")) → "one"
      list.join(Arrays.asList("one", "two")) → "one, two"
      list.join(Arrays.asList("one", "two", "three")) → "one, two, three"
     
      // Join English sentence-like lists.
      ListPhrase list = ListPhrase.from(
        " and ",
        ", ",
        ", and ");
      list.join(Arrays.asList("one")) → "one"
      list.join(Arrays.asList("one", "two")) → "one and two"
      list.join(Arrays.asList("one", "two", "three")) → "one, two, and three"
     
    • Method Detail

      • from

        public static ListPhrase from​(@NonNull
                                      CharSequence separator)
        Entry point into this API.
        Parameters:
        separator - separator for all elements
      • from

        @NonNull
        public static ListPhrase from​(@NonNull
                                      CharSequence twoElementSeparator,
                                      CharSequence nonFinalElementSeparator,
                                      CharSequence finalElementSeparator)
        Entry point into this API.
        Parameters:
        twoElementSeparator - separator for 2-element lists
        nonFinalElementSeparator - separator for non-final elements of lists with 3 or more elements
        finalElementSeparator - separator for final elements in lists with 3 or more elements
      • join

        @NonNull
        public <T> CharSequence join​(@NonNull
                                     T first,
                                     @NonNull
                                     T second,
                                     @NonNull
                                     T... rest)
        Join 3 or more objects using Object.toString() to convert them to Strings.
        Throws:
        IllegalArgumentException - if any of the list elements are null or empty strings.