Java 8 StringJoiner – Java 8的字符串连接器(StringJoiner)

最后修改: 2018年 1月 7日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

StringJoiner is a new class added in Java 8 under java.util package.

StringJoiner是Java 8中java.util包下增加的一个新类。

Simply put, it can be used for joining Strings making use of a delimiter, prefix, and suffix.

简单地说,它可用于连接字符串,并使用分隔符、前缀和后缀。

2. Adding Elements

2.添加元素

We can add Strings using the add() method:

我们可以使用add()方法添加字符串

@Test
public void whenAddingElements_thenJoinedElements() {
    StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
    joiner.add("Red")
      .add("Green")
      .add("Blue");

    assertEquals(joiner.toString(), "[Red,Green,Blue]");
}

If we want to join all elements of a list, we’ll have to loop through the list. Unfortunately, there’s no easy way to do it using StringJoiner:

如果我们想连接一个列表中的所有元素,我们必须循环浏览这个列表。不幸的是,使用StringJoiner没有简单的方法来做到这一点。

@Test
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]");
}

3. Construction

3.建筑

To construct an instance of StringJoiner, we need to mention the delimiter. Optionally, we can also specify the prefix and suffix that should be present in the result:

为了构造一个StringJoiner的实例,我们需要提到分隔符。可选地,我们还可以指定结果中应该出现的前缀和后缀。

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);
}

We use toString() to get the current value from the joiner.

我们使用toString()来从连接器中获取当前值。

Note default values returned by the joiners. A Joiner without prefix and suffix returns an empty String whereas joiner with prefix and suffix returns a String containing both prefix and suffix.

注意由连接器返回的默认值。没有前缀和后缀的连接器会返回一个空的字符串,而有前缀和后缀的连接器会返回一个包含前缀和后缀的字符串

We can change the default String returned by using setEmptyValue():

我们可以通过使用setEmptyValue()改变默认的String返回。

@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");
}

Here, both joiners return the EMPTY_JOINER constant.

这里,两个连接器都返回EMPTY_JOINER常数。

The default value is returned only when the StringJoiner is empty.

只有当StringJoiner为空时,才会返回默认值

4. Merge Joiners

4.合并接头

We can merge two joiners using merge(). It adds the contents of the given StringJoiner without prefix and suffix as the next element:

我们可以使用merge()合并两个连接符。它将给定的StringJoiner 不含前缀和后缀的内容作为下一个元素。

@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]");
}

Note how “-“ is used to concatenate content of cmybJoiner while rgbJoiner still use “,”.

注意“-“如何用于连接cmybJoiner的内容,而rgbJoiner仍然使用“,”.

5. Stream API

5.Stream API

That’s pretty much all that we can do with StringJoiner.

这几乎是我们能用StringJoiner做的所有事情。

There’s one more indirect usage that can be found in the Stream API:

还有一个间接的用法,可以在Stream API中找到。

@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");
}

Collectors.joining() internally uses StringJoiner to perform the joining operation.

Collectors.join()内部使用StringJoiner来执行连接操作。

6. Conclusion

6.结论

In this quick tutorial, we illustrated how to use the StringJoiner class. Overall the StringJoiner seems very primitive and fails to address some basic use cases like joining the elements of a list. It seems to be primarily designed for Collectors.

在这个快速教程中,我们说明了如何使用StringJoiner类。总的来说,StringJoiner似乎非常原始,未能解决一些基本的用例,如连接一个列表的元素。它似乎主要是为Collectors设计的。

If StringJoiner doesn’t meet our requirements, there are other popular and powerful libraries, such as Guava.

如果StringJoiner不能满足我们的要求,还有其他流行的、强大的库,如Guava

And, as usual, all sources can be found over on GitHub.

而且,像往常一样,所有来源都可以在GitHub上找到