JDK 9 RFR Update String.join sample code to use List convenience factory methods

Stuart Marks stuart.marks at oracle.com
Wed Jun 1 01:48:45 UTC 2016


On 5/31/16 6:31 PM, Joseph D. Darcy wrote:
> The String.join javadoc contains some sample code to demonstrate how to use the
> method. The sample code can be improved with the new-in-JDK-9 List convenience
> factory method. Please review this patch to update the sample code:
>
> --- a/src/java.base/share/classes/java/lang/String.java    Tue May 31 17:54:41
> 2016 -0700
> +++ b/src/java.base/share/classes/java/lang/String.java    Tue May 31 18:27:45
> 2016 -0700
> @@ -2424,9 +2424,7 @@
>       *
>       * <blockquote>For example,
>       * <pre>{@code
> -     *     List<String> strings = new LinkedList<>();
> -     *     strings.add("Java");strings.add("is");
> -     *     strings.add("cool");
> +     *     List<String> strings = List.of("Java", "is", "cool");
>       *     String message = String.join(" ", strings);
>       *     //message returned is: "Java is cool"
>       *

This change looks good: +1 for removing a usage of LinkedList, +1 for removing 
multiple statements on the same line, and +1 for using the new JEP 269 API!

> (A corresponding update should *not* be made to the String.join sample using a
> Set since the Set convenience factory methods do not guarantee ordering.)

Correct.

But the Set example is:

>      Set<String> strings = new LinkedHashSet<>();
>      strings.add("Java"); strings.add("is");
>      strings.add("very"); strings.add("cool");
>      String message = String.join("-", strings);

It would be good if you could make the add() calls one per line.

Alternatively, you could do

     Set<String> strings =
         new LinkedHashSet<>(List.of("Java", "is", "very", "cool"));
     String message = String.join("-", strings);

Up to you.

s'marks

"very-cool-Java-is" -- Yoda



More information about the core-libs-dev mailing list