# Java 8 StringJoiner 示例

> 原文： [https://beginnersbook.com/2017/10/java-8-stringjoiner/](https://beginnersbook.com/2017/10/java-8-stringjoiner/)

在 java 8 中，`java.util`包中引入了一个新类`StringJoiner`。使用这个类，我们可以使用指定的分隔符连接多个字符串，我们还可以在连接多个字符串时为最终字符串提供前缀和后缀。在本教程中，我们将看到几个 StringJoiner 类的示例，在本指南的最后，我们将看到 StringJoiner 类的方法。

## Java StringJoiner 示例 1：通过指定分隔符来连接字符串

在这个例子中，我们使用 StringJoiner 连接多个字符串。在创建 StringJoiner 的实例时，我们将分隔符指定为连字符（ - ）。

```java
import java.util.StringJoiner;  
public class Example {  
    public static void main(String[] args) {  
    	// Passing Hyphen(-) as delimiter
        StringJoiner mystring = new StringJoiner("-");    

        // Joining multiple strings by using add() method  
        mystring.add("Logan");  
        mystring.add("Magneto");  
        mystring.add("Rogue");  
        mystring.add("Storm");  

        // Displaying the output String
        System.out.println(mystring);  
    }  
}
```

输出：

```java
Logan-Magneto-Rogue-Storm
```

## Java StringJoiner 示例 2：为输出 String 添加前缀和后缀

```java
import java.util.StringJoiner;  
public class Example {  
    public static void main(String[] args) {  
    	/* Passing comma(,) as delimiter and opening bracket
    	 * "(" as prefix and closing bracket ")" as suffix
    	 */
        StringJoiner mystring = new StringJoiner(",", "(", ")");    

        // Joining multiple strings by using add() method  
        mystring.add("Negan");  
        mystring.add("Rick");  
        mystring.add("Maggie");  
        mystring.add("Daryl");  

        // Displaying the output String
        System.out.println(mystring);  
    }  
}
```

Output:

```java
(Negan,Rick,Maggie,Daryl)
```

## StringJoiner 示例 3：合并两个 StringJoiner 对象

```java
import java.util.StringJoiner;  
public class Example {  
   public static void main(String[] args) {  
	/* Passing comma(,) as delimiter and opening bracket
	 * "(" as prefix and closing bracket ")" as suffix
	 */
	StringJoiner mystring = new StringJoiner(",", "(", ")");    

	mystring.add("Negan");  
	mystring.add("Rick");  
	mystring.add("Maggie");  
	mystring.add("Daryl");  

	System.out.println("First String: "+mystring);

	/* Passing hyphen(-) as delimiter and string "pre"
	 * as prefix and string "suff" as suffix
	 */
	StringJoiner myanotherstring = new StringJoiner("-", "pre", "suff");    

	myanotherstring.add("Sansa");  
	myanotherstring.add("Imp");  
	myanotherstring.add("Jon");  
	myanotherstring.add("Ned"); 

	System.out.println("Second String: "+myanotherstring);

	/* Merging both the strings  
	 * The important point to note here is that the output string will be 
	 * having the delimiter prefix and suffix of the first string (the string
	 * which is calling the merge method of StringJoiner)
	 */
	StringJoiner mergedString = mystring.merge(myanotherstring);   
	System.out.println(mergedString);  
   }  
}
```

Output:

```java
First String: (Negan,Rick,Maggie,Daryl)
Second String: preSansa-Imp-Jon-Nedsuff
(Negan,Rick,Maggie,Daryl,Sansa-Imp-Jon-Ned)
```

在上面的例子中，我们已经看到了 StringJoiner 类的 add（）和 merge（）方法。让我们看看这个类的其他方法。

## StringJoiner 示例：setEmptyValue（），length（）和 toString（）方法

```java
import java.util.StringJoiner;  
public class Example {  
    public static void main(String[] args) {  
    	//Comma(,) as delimiter
        StringJoiner mystring = new StringJoiner(",");   

        /* Using setEmptyValue() method, we can set the default value
         * of a StringJoiner instance, so if the StringJoiner is empty
         * and we print the value of it, this default value will be
         * displayed
         */
        mystring.setEmptyValue("This is a default String");  

        /* We have not added any string to StringJoiner yet so
         * this should display the default value of StringJoiner
         */
        System.out.println("Default String: "+mystring);  

        // Adding strings to StringJoiner  
        mystring.add("Apple");  
        mystring.add("Banana"); 
        mystring.add("Orange");
        mystring.add("Kiwi");
        mystring.add("Grapes");
        System.out.println(mystring);  

        /* The length() method of StringJoiner class returns the 
         * length of the string (the number of characters in the 
         * StringJoiner instance)
         */
        int length = mystring.length();  
        System.out.println("Length of the StringJoiner: "+length);  

        /* The toString() method is used for converting a StringJoiner
         *  instance to a String. 
         */
        String s = mystring.toString();  
        System.out.println(s);   
    }  
}
```

Output:

```java
Default String: This is a default String
Apple,Banana,Orange,Kiwi,Grapes
Length of the StringJoiner: 31
Apple,Banana,Orange,Kiwi,Grapes

```

**参考文献：**
[Java 8 - StringJoiner JavaDoc](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html)