guava是goog1e开源的一套针对java api的扩展工具包,里面包含很多非常实用的方法,在工作中可以提高我们的编码效率;

1.Joiner

将集合按指定字符拼接成字符串;

private final List stringList = Arrays.asList(
        "tom","jack","bob");

private final List stringListWithNullValue = Arrays.asList(
        "tom","jack","bob",null,"rose");

@Test
public void testJoin(){
    String join = Joiner.on("#").join(stringList);
    assertThat(join,equalTo("tom#jack#bob"));
}

// 跳过list中的null
@Test
public void testJoinOnJoinSkipNull(){
    String join = Joiner.on("#").skipNulls().join(stringListWithNullValue);
    assertThat(join,equalTo("tom#jack#bob#rose"));
}

// 替换null为指定字符
@Test
public void testJoinOnJoinUseForNull(){
    String join = Joiner.on("#").useForNull("NULL").join(stringListWithNullValue);
    assertThat(join,equalTo("tom#jack#bob#NULL#rose"));
}

// appendTo
@Test
public void testJoinOnJoinAppendTo(){
    final StringBuilder buffer = new StringBuilder("TEST");
    StringBuilder buffer_new = Joiner.on("#").appendTo(buffer, stringList);
    assertThat(buffer_new.toString(),equalTo("TESTtom#jack#bob"));
}

private final Map stringMap = ImmutableMap.of("a","b","c","d");

/**
 * 对Map kv拆分
 */
@Test
public void testJoinOnWithMap(){
    assertThat(Joiner.on("#").withKeyValueSeparator("=").join(stringMap),equalTo("a=b#c=d"));
}

2.Splitter

Splitter主要是分隔字符串为List或Map

@Test
public void testSplitter(){
    List stringList = Splitter.on("|").splitToList("hello|word");
    assertThat(stringList,notNullValue());
    assertThat(stringList.size(),equalTo(2));
}

@Test
public void testSplitter_OmitEmpty(){
    List stringList = Splitter.on("|").omitEmptyStrings().splitToList("hello|word||||");
    assertThat(stringList,notNullValue());
    assertThat(stringList.size(),equalTo(2));
}

@Test
public void testSplitter_TrimResult(){
    List stringList = Splitter.on("|").trimResults().omitEmptyStrings().splitToList(" hello | word||||");
    assertThat(stringList,notNullValue());
    assertThat(stringList.size(),equalTo(2));
}

@Test
public void testSplitter_FixLeng(){
    List result = Splitter.fixedLength(4).splitToList("aaaabbbbccccdddd");
    assertThat(result,notNullValue());
    assertThat(result.size(),equalTo(4));
    assertThat(result.get(0),equalTo("aaaa"));
}

@Test
public void testSplitter_Limit(){
    List result = Splitter.on("#").limit(3).splitToList("aaaa#bbbb#cccc#dddd");
    assertThat(result,notNullValue());
    assertThat(result.size(),equalTo(3));
    assertThat(result.get(2),equalTo("cccc#dddd"));
}

// 转Map
@Test
public void testSplitter_SplitToMap(){
    Map split = Splitter.on("|").withKeyValueSeparator("=").split("a=b|c=d");
    assertThat(split,notNullValue());
    assertThat(split.size(),equalTo(2));
    assertThat(split.get("a"),equalTo("b"));
}