Joiner的用法

Joiner是guava.jar包下的一个类,将数组,集合,map等类型用指定的字符进行分割。

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>23.0</version>
</dependency>

 

1.对数组进行分割-----join

@Test
public void testStringJoin() {
  String str[] = { "aaa", "vbbb", "ccc", "ddd" };
  String ss = Joiner.on("==").join(str);

  System.out.println(ss);//aaa==vbbb==ccc==ddd
}

 

2.对List进行分割,替换集合中的Null值---useForNull

@Test
public void testUseForNull() {
  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, null, 6);

  String str = Joiner.on(";").useForNull("*").join(list);

  System.out.println(str);//1;2;3;4;5;*;6
}

 

3.对List进行分割,消除集合中的Null值----skipNulls

@Test
public void testSkipNulls() {
  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, null, 6);

  String str = Joiner.on("==").skipNulls().join(list);

  System.out.println(str);//1==2==3==4==5==6
}

 

4.对StringBuilder或StringBuffer进行追加----appendTo

@Test
public void testAppendTo() {
  StringBuilder stringBuilder = new StringBuilder("aaa_");
  List<String> strs = Arrays.asList("bbb", "ccc", "ddd");

  StringBuilder sb = Joiner.on("_").appendTo(stringBuilder, strs);

  System.out.println(sb.toString());//aaa_bbb_ccc_ddd

}

 

5.对Map进行分割-----withKeyValueSeparator

@Test
public void testMapJoiner() {
  Map<String, String> map = new HashMap<String, String>();
  map.put("name", "张三");
  map.put("age", "13");
  map.put("sex", "M");
  String str = Joiner.on("&").withKeyValueSeparator("=").join(map);

  System.out.println(str);//sex=M&name=张三&age=13
}

 

posted @ 2018-11-29 09:40  真某人  阅读(594)  评论(0编辑  收藏  举报