Skip to content

Instantly share code, notes, and snippets.

@bsharathchand
Last active August 29, 2015 14:26
Show Gist options
  • Save bsharathchand/8f6bce3f753dc0e62d9b to your computer and use it in GitHub Desktop.
Save bsharathchand/8f6bce3f753dc0e62d9b to your computer and use it in GitHub Desktop.
String concatenation in Java 8

String concatenation before and after Java 8

Problem: To print a concatenated String like "Chennai and Hyderabad and Bangalore and Delhi" from an array ["Chennai", "Hyderabad", > "Bangalore", "Delhi"]

Before StringJoiner

final String delemiter = " and ";
String[] cities = new String[]{"Chennai", "Hyderabad", "Bangalore", "Delhi"};
StringBuilder outputStr;
if(cities.length == 0 ){ // Check for no content
  outputStr = new StringBuilder("No Content");
}else{
  for(String city : cities) { // loop for each element
    outputStr.append(city);
    outputStr.append(delemiter);
  }
  outputStr.replaceLast(delemiter); // remove the last delemeter
}
System.out.println("prefix"+outputStr.toString()+"suffix"); //appending prefix or suffix if needed

After Java 8 String Join method

String[] cities = new String[]{"Chennai", "Hyderabad", "Bangalore", "Delhi"};
String output = cities.length == 0 ? "No Content" : String.join(" and ",cities);
System.out.println("prefix"+output+"suffix"); //appending prefix or suffix if needed

Using the static join method of String class we compacted the logic of 10 lines into 1 line.

After Java 8 StringJoiner

String[] cities = new String[]{"Chennai", "Hyderabad", "Bangalore", "Delhi"};
// StringJoiner joiner = new StringJoiner("prefix", "delimeter", "suffix"); // if prefix and suffix are needed
StringJoiner joiner = new StringJoiner(" and "); // only delemiter passed
Arrays.asList(cities).forEach(city -> joiner.add(city));
System.out.println(outputStr.toString()); //prefix and suffix will be added based of the constructor args..

By using the StringJoiner, we reduced the LOC by more than 50%. Such is the power of Lambdas and StringJoiner.

Though it might seem, String#join is the best way for this example, StringJoiner class provides much more flexibility by enabling us to merge the items from different collections or even different StringJoiner objects to get one big concatenated OUTPUT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment