Monday 19 February 2018

Java 8 - Join Strings Easily


(Download One Minute Java Mobile app for latest updates)

StringJoiner
StringJoiner class of package java.util.StringJoiner is very helpful for joining delimiter seprated string.
It is used to build a characters sequence separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Example


 If we want to create a string of names seperated by ':' and enclosed in '[' ']' braces than we can write   code as below

 StringJoiner sj = new StringJoiner(":", "[", "]"); ----> 1
 sj.add("George");
 sj.add("Sally");
 sj.add("Fred");
 String requiredString = sj.toString();

 If we print 'requiredString' the output will be as below.

 "[George:Sally:Fred]"

 Note : In line 1 of above example delimiter ':' is compulsory parameter and the prefix '[' and sufix ']'   are optional parameters


Static join() of String
Static method join() from String class is very handy for joining strings in collections

Example


 Set stringSet = new HashSet();
 stringSet.add("Sachin");
 stringSet.add("Rahul");
 stringSet.add("Saurav");
 String newString = String.join(",", stringSet);


 If we print 'newString' the output will be as below.
 "Saurav,Rahul,Sachin"


No comments:

Post a Comment