JDK1.8之String.join()

记录

今天在阅读 String 源码时,无意间看到了这个方法,以前也没有见过用过,那么就要好好研究一下。

源码

//返回一个新的String,该String由CharSequence元素的副本组成,这些元素与指定的副本连接在一起。
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"
      }
      
	  //如果元素为空,则添加"null"。
      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();
}

//第二个方法可供可使用迭代器的集合类型的集合使用
public static String join(CharSequence delimiter,
            Iterable elements) {
        Objects.requireNonNull(delimiter);
        Objects.requireNonNull(elements);
        StringJoiner joiner = new StringJoiner(delimiter);
        for (CharSequence cs: elements) {
            joiner.add(cs);
        }
        return joiner.toString();
}

示例

以前我们想在字符串中间添加字符时,就要考虑头和尾,现在有了这个方法,它只会为元素中两个元素之间添加,是不是方便了很多!

JDK1.8之String.join()_第1张图片

输出结果:

最后,深感Java编写者的聪明才智如此强大!

你可能感兴趣的:(源码阅读,JavaCore)