join
返回由delimiter 连接的副本和指定的副本组成的新字符串 。
请注意,如果元素为空,则"null" 添加。
语法:
join(CharSequence delimiter, CharSequence... elements)
join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
参数:
delimiter - 分隔每个元素的分隔符
elements - 要连接在一起的元素。
返回:
一个新String 的,由elements 分隔的组成delimiter
抛出:
NullPointerException` -如果`delimiter`或是`elements``null
自从:
1.8
实例
String message = String.join("-", "Java", "is", "cool");
// message returned is: "Java-is-cool"
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"
源码
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();
}
|