您当前的位置: 首页 > 

Dongguo丶

暂无认证

  • 2浏览

    0关注

    472博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【JDK源码分析】 String.join()方法解析

Dongguo丶 发布时间:2018-11-27 21:22:41 ,浏览量:2

今天看书的时候看到String.join方法时,发现和我想的结果不太一样,所以点开源码看一看String.join方法到底是实现了什么,

原来String在JDK 8中新增了join方法

    /**
     * Returns a new String composed of copies of the
     * {@code CharSequence elements} joined together with a copy of
     * the specified {@code delimiter}.
     *
     * For example,
     * 
{@code
     *     String message = String.join("-", "Java", "is", "cool");
     *     // message returned is: "Java-is-cool"
     * }
* * Note that if an element is null, then {@code "null"} is added. * * @param delimiter the delimiter that separates each element * @param elements the elements to join together. * * @return a new {@code String} that is composed of the {@code elements} * separated by the {@code delimiter} * * @throws NullPointerException If {@code delimiter} or {@code elements} * is {@code null} * * @see java.util.StringJoiner * @since 1.8 */ public static String join(CharSequence delimiter, CharSequence... elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); // Number of elements not likely worth Arrays.stream overhead. StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs: elements) { joiner.add(cs); } return joiner.toString(); } /** * Returns a new {@code String} composed of copies of the * {@code CharSequence elements} joined together with a copy of the * specified {@code delimiter}. * * For example, *
{@code
     *     List strings = new LinkedList();
     *     strings.add("Java");strings.add("is");
     *     strings.add("cool");
     *     String message = String.join(" ", strings);
     *     //message returned is: "Java is cool"
     *
     *     Set strings = new LinkedHashSet();
     *     strings.add("Java"); strings.add("is");
     *     strings.add("very"); strings.add("cool");
     *     String message = String.join("-", strings);
     *     //message returned is: "Java-is-very-cool"
     * }
* * Note that if an individual element is {@code null}, then {@code "null"} is added. * * @param delimiter a sequence of characters that is used to separate each * of the {@code elements} in the resulting {@code String} * @param elements an {@code Iterable} that will have its {@code elements} * joined together. * * @return a new {@code String} that is composed from the {@code elements} * argument * * @throws NullPointerException If {@code delimiter} or {@code elements} * is {@code null} * * @see #join(CharSequence,CharSequence...) * @see java.util.StringJoiner * @since 1.8 */ public static String join(CharSequence delimiter, Iterable
关注
打赏
1638062488
查看更多评论
0.0376s