guava教程——Joiner、Splitter

拈花ヽ惹草 提交于 2020-04-08 11:39:51

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

1.Joiner

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

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

private final List<String> 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<String,String> 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<String> stringList = Splitter.on("|").splitToList("hello|word");
    assertThat(stringList,notNullValue());
    assertThat(stringList.size(),equalTo(2));
}

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

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

@Test
public void testSplitter_FixLeng(){
    List<String> 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<String> 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<String, String> split = Splitter.on("|").withKeyValueSeparator("=").split("a=b|c=d");
    assertThat(split,notNullValue());
    assertThat(split.size(),equalTo(2));
    assertThat(split.get("a"),equalTo("b"));
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!