String join()
今天刷LeetCode的时候看题析,看到一个未曾使用过的方法String.join()
/** * Creates a new String by putting each element together joined by the delimiter. If an element is null, then "null" is used as string to join. * * @param delimiter * Used as joiner to put elements together * @param elements * Elements to be joined * @return string of joined elements by delimiter * @throws NullPointerException * if one of the arguments is null * */ public static String join(CharSequence delimiter, CharSequence... elements) { StringJoiner stringJoiner = new StringJoiner(delimiter); for (CharSequence element : elements) { stringJoiner.add(element); } return stringJoiner.toString(); }
注释说明这个方法是将后面的可变参数的内容通过前面的delimiter分隔符连接在一起,如果一个内容是null,那么“null”将会作为字符串放到连接中。
可以看到这里新建了一个StringJoiner对象,里面的具体实现往后再看,这里我们只需要明白这个方法是将elements中的对象通过delimiter连接起来就行,例如:
List names=new ArrayList<String>(); names.add("1"); names.add("2"); names.add("3"); System.out.println(String.join("-", names)); String[] arrStr=new String[]{"a","b","c"}; System.out.println(String.join("-", arrStr)); 输出: 1-2-3 a-b-c