在开发过程中,有时候需要打印集合中的对象的某个属性,为了格式化以前常用StrinigBuffer。
比如下面这种代码:
Set catSet = new HashSet<>(2);
@Before
public void init() {
Cat cat = new Cat();
cat.setName("老大");
cat.setAge(1);
catSet.add(cat);
Cat cat2 = new Cat();
cat2.setName("老二");
cat2.setAge(2);
catSet.add(cat2);
}
@Test
public void print1() {
// 给出友好提示
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
Iterator iterator = catSet.iterator();
int seq = 0;
while (iterator.hasNext()) {
seq++;
stringBuilder.append(seq);
stringBuilder.append(":");
stringBuilder.append(iterator.next().getName());
if (seq != catSet.size()) {
stringBuilder.append(",");
}
}
stringBuilder.append("]");
Assert.assertEquals("[1:老二,2:老大]", stringBuilder.toString());
}
最近接触到Java8提供了StringJoiner,看到一篇不错的文章,翻译在此,文后给出改进方案,一行代码解决问题!。
--------------------------------------------分割线-------------------------------------------------------------
@Test
public void whenAddingElements_thenJoinedElements() {
StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
joiner.add("Red")
.add("Green")
.add("Blue");
assertEquals(joiner.toString(), "[Red,Green,Blue]");
}
如果想讲List添加到其中:
@Test
public void whenAddingListElements_thenJoinedListElements() {
List 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 = "]";
@Test
public void whenEmptyJoinerWithoutPrefixSuffix_thenEmptyString() {
StringJoiner joiner = new StringJoiner(",");
assertEquals(0, joiner.toString().length());
}
@Test
public void whenEmptyJoinerJoinerWithPrefixSuffix_thenPrefixSuffix() {
StringJoiner joiner = new StringJoiner(
",", PREFIX, SUFFIX);
assertEquals(joiner.toString(), PREFIX + SUFFIX);
}
toString() 方法得到当前连接对象的字符串形式。
没有指定前缀和后缀的Joiner对象将返回空字符串。
@Test
public void whenEmptyJoinerWithEmptyValue_thenDefaultValue() {
StringJoiner joiner = new StringJoiner(",");
joiner.setEmptyValue("default");
assertEquals(joiner.toString(), "default");
}
@Test
public void whenEmptyJoinerWithPrefixSuffixAndEmptyValue_thenDefaultValue() {
StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
joiner.setEmptyValue("default");
assertEquals(joiner.toString(), "default");
}
可以调用joiner.setEmptyValue()函数,设置默认值。
private String PREFIX = "[";
private String SUFFIX = "]";
@Test
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]");
}
两个joiner可以通过merge函数,组合在一起。
@Test
public void whenUsedWithinCollectors_thenJoined() {
List rgbList = Arrays.asList("Red", "Green", "Blue");
String commaSeparatedRGB = rgbList.stream()
.map(color -> color.toString())
.collect(Collectors.joining(","));
assertEquals(commaSeparatedRGB, "Red,Green,Blue");
}
英文原文:https://www.baeldung.com/java-string-joiner
--------------------------------------------分割线-------------------------------------------------------------
根据本文的学习对我们的代码进行改进:
第一版:
@Test
public void print() {
StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
Iterator iterator = catSet.iterator();
int seq = 0;
while (iterator.hasNext()) {
seq++;
stringJoiner.add(seq + ":" + iterator.next().getName());
}
Assert.assertEquals("[1:老二,2:老大]", stringJoiner.toString());
}
第二版:
@Test
public void print2() {
List catList = new ArrayList<>(catSet);
String result = IntStream.range(0,catList.size()).mapToObj(i->i+":"+ catList.get(i).getName()).collect(Collectors.joining(",", "[", "]"));
Assert.assertEquals("[1:老二,2:老大]", result);
}
一行代码,很简单,很优雅!!!
网上的一些其他例子:https://www.codota.com/code/java/classes/java.util.StringJoiner?openFrom=IDE_plugin_2.8.3
另外这个网站可以搜到很多很多很多类的用法,推荐收藏!
如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。