String.join() --Java8中String类新增方法
序言
在看别人的代码时发现一个方法String.join(),因为之前没有见过所以比较好奇。
跟踪源码发现源码很给力,居然有用法示例,以下是源码:
/** * Returns a new String composed of copies of the * {@code CharSequence elements} joined together with a copy of * the specified {@code delimiter}. * //这是用法示例 * <blockquote>For example, * <pre>{@code * String message = String.join("-", "Java", "is", "cool"); * // message returned is: "Java-is-cool" * }</pre></blockquote> * * 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}. * * <blockquote>For example, * <pre>{@code * List<String> strings = new LinkedList<>(); * strings.add("Java");strings.add("is"); * strings.add("cool"); * String message = String.join(" ", strings); * //message returned is: "Java is cool" * * Set<String> 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" * }</pre></blockquote> * * 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<? extends CharSequence> elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs: elements) { joiner.add(cs); } return joiner.toString(); }
总结
String类中的join()方法有两种,第一种
join(CharSequence delimiter, CharSequence... elements)
这里join()方法第二个参数表示参数的个数不确定,可以接受任意多个,就像示例中的写法那样。
第二种
join(CharSequence delimiter,
Iterable<? extends CharSequence> elements)
这种写法第二个参数中涉及到一个泛型的用法,这个写法表示,Iterable中存放的内容需要是CharSequence这个类的子类。