Guava Joiner

背景

Java中,需要将List中的元素拼接成字符串

Joiner

引入

maven项目可引入如下依赖:

1
2
3
4
5
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>

字符串拼接

1
String result =  Joiner.on("_").join(list);

跳过null值

1
2
String result = Joiner.on("; ").skipNulls().join("Harry", null, "Ron", "Hermione");
//输出:Harry; Ron; Hermione

替换null值

1
2
String result = Joiner.on("; ").useForNull("null").join("Harry", null, "Ron", "Hermione");
// 输出:Harry; null; Ron; Hermione

将集合转换为String

1
2
String result = Joiner.on(",").join(Arrays.asList(1, 5, 7));
//输出:1,5,7

将Map转换为String

1
2
3
Map map = ImmutableMap.of("k1", "v1", "k2", "v2");
result = Joiner.on("; ").withKeyValueSeparator("=").join(map);
// 输出:k1=v1; k2=v2