BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java 8 StringJoiner with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In java 8, a new class StringJoiner is introduced in the java.util package. Using this class we can join more than one strings with the specified delimiter, we can also provide prefix and suffix to the final string while joining multiple strings. In this tutorial we will see several examples of StringJoiner class and at the end of this guide, we will see the methods of StringJoiner class.

Java StringJoiner Example 1: Joining strings by specifying delimiter

In this example, we are concatenating multiple strings using StringJoiner. While creating the instance of StringJoiner, we have specified the delimiter as hyphen(-).

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

Output:

Logan-Magneto-Rogue-Storm

Java StringJoiner Example 2: Adding prefix and suffix to the output String

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:

(Negan,Rick,Maggie,Daryl)

StringJoiner Example 3: Merging two StringJoiner objects

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:

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

In the above examples, we have seen the add() and merge() methods of StringJoiner class. Lets see the other methods of this class.

StringJoiner Example: setEmptyValue(), length() and toString() methods

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:

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

References:
Java 8 – StringJoiner JavaDoc

❮ PreviousNext ❯

Top Related Articles:

  1. How to Split a String in Java with Delimiter
  2. Convert Comma Separated String to HashSet in Java
  3. Java Functional Interfaces
  4. Java String length() Method with examples
  5. Comparator Interface in Java

Tags: Java8-Features

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap