guava教程——JoinerSplitter
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了guava教程——JoinerSplitter相关的知识,希望对你有一定的参考价值。
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"));
}
以上是关于guava教程——JoinerSplitter的主要内容,如果未能解决你的问题,请参考以下文章