Guava的Joiner的日常使用

2023-12-25 17:09:11
具体使用参考官方文档:https://github.com/google/guava/wiki/StringsExplained#joiner

//1 处理,为null的值,替换
String join = Joiner.on("_").useForNull("*").join("1", "2", 90, 100,110,109,200,202,400,500);
System.out.println(join);

//2 处理,为null的值,略过
String join2  = Joiner.on("_").skipNulls().join(1,3,4354);
System.out.println(join2);

//3 对数组分隔
String [] arrays = new String[]{"11","22","33"};
String join3 = Joiner.on("_").join(arrays);
System.out.println(join3);
Assert.equals(join3,"11_22_33");

//4 对list分隔
List list = Arrays.asList(null, 1, 2, null, 3, 4, 6, null);
String join4 = Joiner.on("_").skipNulls().join(list);
System.out.println(join4);

//5 对StringBuilder进行追加
StringBuilder builder = new StringBuilder();
builder.append("te");
List listTest = Lists.newArrayList(null,1,2,null,3,4,6,null);
StringBuilder sb = Joiner.on("").skipNulls().appendTo(builder,listTest);
System.out.println(sb.toString());

//6 对map进行分隔,用withKeyValueSeparator,map的key或者value为null,一定要用useForNull,否则key和value均不允许null
Map<String,String> map = new HashMap<>();
map.put("1key","1");
map.put("2key","2");
map.put(null,"3");
String mapString = Joiner.on("&").withKeyValueSeparator("=").useForNull("nullValue").join(map);
System.out.println(mapString);

//7 对文件进行追加,只要是实现了Appendable接口的类均可以用Joiner来处理
FileWriter fileWriter = new FileWriter("C:\\Users\\tangqing\\Desktop\\test.apk.txt");
String [] arraysFile = new String[]{"11","22","33"};
FileWriter writer = Joiner.on("_").appendTo(fileWriter, arraysFile);

// 8
Preconditions.checkNotNull(fileWriter, "appendable");

文章来源:https://blog.csdn.net/qing419925094/article/details/135201559
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。