Google Guava常用类-Joiner
作者:互联网
例:
Joiner joiner = Joiner.on("; ").skipNulls(); . . . return joiner.join("Harry", null, "Ron", "Hermione"); // Harry; Ron; Hermione
如果参数有null且没有用skipNulls()或useForNull(String)会抛NullPointerException
A appendTo(A appendable, Iterable<?> parts)
Appendable接口 可追加
实现类 BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer
用法
String[] arr = {"a","b","c"}; StringBuilder ab = new StringBuilder("start: "); StringBuilder ac = Joiner.on("").appendTo(ab,arr); System.out.println(ab); // start: abc System.out.println(ac); // start: abc
A appendTo(A appendable, @Nullable Object first, @Nullable Object second, Object… rest)
向appendable参数后追加first、second…所有参数
String join(Iterable<?> parts)
将可迭代的参数中所有子元素连接。
static Joiner on(char separator)
为static对象设置分隔符
Joiner实例不可变,即用final修饰,一旦初始化不可变,所以分步调用joiner的静态函数是不起作用的。如:
Joiner joiner = Joiner.on(','); joiner.skipNulls(); // does nothing! return joiner.join("wrong", null, "wrong");
这样使得joiner线程安全,并且返回的都是final static常量
Joiner skipNulls()
Joiner useForNull(String nullText)
Joiner.MapJoiner withKeyValueSeparator(String keyValueSeparator)
Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "a"); map.put(2, "b"); Joiner.MapJoiner joiner = Joiner.on(";").withKeyValueSeparator("->"); System.out.println(joiner.join(map)); // 1->a;2->b
总结:
标签:skipNulls,Google,join,String,Guava,StringBuilder,Joiner,joiner 来源: https://www.cnblogs.com/jelly12345/p/16575072.html