Java StringJoiner

时间:2022-09-11 21:13:36

Java StringJoiner

Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix and suffix to the char sequence.

import java.util.StringJoiner;

public class StringJoinerExample {
public static void main(String[] args) {
// passing comma(,) as delimiter
StringJoiner joinNames = new StringJoiner(",");
// Adding values to StringJoiner
joinNames.add("Rahul");
joinNames.add("Raju");
joinNames.add("Peter");
joinNames.add("Raheem");
System.out.println(joinNames); // passing comma(,) and square-brackets as delimiter
StringJoiner joinNames2 = new StringJoiner(",", "[", "]");
// Adding values to StringJoiner
joinNames2.add("Rahul");
joinNames2.add("Raju");
joinNames2.add("Peter");
joinNames2.add("Raheem");
System.out.println(joinNames2); StringJoiner joinNames3 = new StringJoiner(",", "[", "]");
joinNames3.add("Rahul");
joinNames3.add("Raju"); StringJoiner joinNames4 = new StringJoiner(":", "[", "]");
joinNames4.add("Peter");
joinNames4.add("Raheem"); // Merging two StringJoiner
StringJoiner merge = joinNames3.merge(joinNames4);
System.out.println(merge);
}
}

点击查看结果

```
Rahul,Raju,Peter,Raheem
[Rahul,Raju,Peter,Raheem]
[Rahul,Raju,Peter:Raheem]
```
import java.util.StringJoiner;

public class StringJoinerMethodExample {
public static void main(String[] args) {
StringJoiner joinNames = new StringJoiner(","); // Prints nothing because it is empty
System.out.println(joinNames); // We can set default empty value.
joinNames.setEmptyValue("It is empty");
System.out.println(joinNames); // Adding values to StringJoiner
joinNames.add("Rahul");
joinNames.add("Raju");
System.out.println(joinNames); // Returns length of StringJoiner
int length = joinNames.length();
System.out.println("Length: " + length); // Returns StringJoiner as String type
String str = joinNames.toString();
System.out.println(str); // Now, we can apply String methods on it
char ch = str.charAt(3);
System.out.println("Character at index 3: " + ch); // Adding one more element
joinNames.add("Sorabh");
System.out.println(joinNames); // Returns length
int newLength = joinNames.length();
System.out.println("New Length: " + newLength);
}
}

点击查看结果

```

It is empty

Rahul,Raju

Length: 10

Rahul,Raju

Character at index 3: u

Rahul,Raju,Sorabh

New Length: 17

</div>

**参考资料**
* [https://www.javatpoint.com/java-stringjoiner](https://www.javatpoint.com/java-stringjoiner)