1. 添加元素
public void () {
StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
joiner.add("Red")
.add("Green")
.add("Blue");
assertEquals(joiner.toString(), "[Red,Green,Blue]");
}
2. 使用for循环添加内容
public void whenAddingListElements_thenJoinedListElements() {
List<String> rgbList = new ArrayList<>();
rgbList.add("Red");
rgbList.add("Green");
rgbList.add("Blue");
StringJoiner rgbJoiner = new StringJoiner(
",", PREFIX, SUFFIX);
for (String color : rgbList) {
rgbJoiner.add(color);
}
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}
使用构造方式
private String PREFIX = "[";
private String SUFFIX = "]";
public void whenEmptyJoinerWithoutPrefixSuffix_thenEmptyString() {
StringJoiner joiner = new StringJoiner(",");
assertEquals(0, joiner.toString().length());
}
public void whenEmptyJoinerJoinerWithPrefixSuffix_thenPrefixSuffix() {
StringJoiner joiner = new StringJoiner(
",", PREFIX, SUFFIX);
assertEquals(joiner.toString(), PREFIX + SUFFIX);
}
合并Joiner
public void whenMergingJoiners_thenReturnMerged() {
StringJoiner rgbJoiner = new StringJoiner(
",", PREFIX, SUFFIX);
StringJoiner cmybJoiner = new StringJoiner(
"-", PREFIX, SUFFIX);
rgbJoiner.add("Red")
.add("Green")
.add("Blue");
cmybJoiner.add("Cyan")
.add("Magenta")
.add("Yellow")
.add("Black");
rgbJoiner.merge(cmybJoiner);
assertEquals(
rgbJoiner.toString(),
"[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
}
使用流
@Test
public void whenUsedWithinCollectors_thenJoined() {
List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
String commaSeparatedRGB = rgbList.stream()
.map(color -> color.toString())
.collect(Collectors.joining(","));
assertEquals(commaSeparatedRGB, "Red,Green,Blue");
}
3、总结
分割字符串使用StringJoiner方式很不错,也可以使用流的方式,两个字符串拼接merge也挺好用。