Hello guys, joining multiple String literals or objects into one is a common programming requirement and you will often find situations where you need to convert a list of String or a Collection of String into a CSV String for your application. For a long time, JDK API has no way to join multiple String literals or objects together, which forces programmers to write hacks like looping through all String objects and manually joining them using String concatenation to create the final, joined String. Even though this approach worked, it was filled with errors and hacks like you need to be careful not to add delimiter before the first element and after the last element, which often caused issues, particularly in the case of beginners and junior Java developers.
But the bigger problem with that approach was that everyone needs to re-invent the wheel. Since it was a very common requirement you will find many programmers writing the same routines and making the same mistakes and often ending in StackOverflow to solve their problems. Thankfully Java 8 solved this problem once for all.
The JDK 8 API provides a couple of more ways to join Strings like you can join String by using the StringJoiner class or you can join the String by calling the String.join() method.
In this article, we'll explore both these ways to join string and understand what is the difference between them, the pros and cons of each approach, and when to use StringJoiner and when String.join() is a better option.
Btw, Java 8 and other new version has introduced many such goodies, which often goes unnoticed, if you want to learn more about them I suggest you go through a comprehensive Java course like The Complete Java Masterclass which is also the most up-to-date course, recently updated for Java 12.
The JDK 8 API has added a new class called java.util.StringJoiner which allows you to join more than one String using a specified delimiter or joiner. For example, you can join multiple strings separated by comma (,) to create a CSV String, Or even better, you can create a full path for a directory in Linux by joining String using forward slash "/" as explained by Cay. S. Horstmann in the Java SE 9 for the Impatient, my favorite book to learn Java.
Here is an example:
This will give you a string like "usr/local/bin" which you can pass it to any program. You can further add a "/" using prefix if you want to use it as an absolute path or use it like this if you need a relative path.
One more advantage of StringJoiner is the fluent API it offers which means you can write code in one line. For example, the above code can be re-written as following using fluent methods of StringJoiner:
This will print:
If you are interested in other Java 8 features then you can also see the What's New in Java 8 course on Pluralsight, one of the clearest and concise online courses to learn Java 8. Btw, you would need a Pluralsight membership to access this course, Alternative, you can also use their 10-day-free-trial to join this course for FREE.
here is an example of using String.join() method to join multiple String literals in Java:
This will print the following String:
Which is quite good because now you don't need to worry about not adding delimiter at the start or removing it from the end, one of the common problems you face while manually joining multiple String together in a loop separated by a delimiter as shown earlier in my example of generating CSV String in Java.
Another advantage of String.join() method is that you can now directly convert a list of String into a CSV String in Java, without writing any manual code, here is an example of how to do it.
This will print the following String:
That's cool, isn't it? Now you are free from converting a list of String or set of String to a CSV String manually in Java. It's also worth noting that String.join() internally uses StringJoiner class for joining String literals. See The Complete Java MasterClass course on Udemy learn more about this and many such goodies from Java 8 and other higher Java versions.
That's all about 2 ways to join String in Java 8. Now, you can finally join the String in Java 8 without using a third-party library and you also have options to use the class which makes sense for you. In general, join() method of String class is more convenient because you can directly call and pass both delimeter and individual String objects which need to be joined.
I mean, you don't need to create another object like StringJoiner. It also allows you to join String from a Collection class like ArrayList or LinkedList, which means you can create a comma-separated String from an ArrayList of String, how cool is that?
P.S.: If you just want to learn more about new features in Java 8 then please see the course What's New in Java 8. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API and other miscellaneous changes
But the bigger problem with that approach was that everyone needs to re-invent the wheel. Since it was a very common requirement you will find many programmers writing the same routines and making the same mistakes and often ending in StackOverflow to solve their problems. Thankfully Java 8 solved this problem once for all.
The JDK 8 API provides a couple of more ways to join Strings like you can join String by using the StringJoiner class or you can join the String by calling the String.join() method.
In this article, we'll explore both these ways to join string and understand what is the difference between them, the pros and cons of each approach, and when to use StringJoiner and when String.join() is a better option.
Btw, Java 8 and other new version has introduced many such goodies, which often goes unnoticed, if you want to learn more about them I suggest you go through a comprehensive Java course like The Complete Java Masterclass which is also the most up-to-date course, recently updated for Java 12.
Joining String using StringJoiner in Java 8
Here is an example:
StringJoiner joiner = new StringJoiner("/"); joiner.add("usr"); joiner.add("local"); joiner.add("bin");
This will give you a string like "usr/local/bin" which you can pass it to any program. You can further add a "/" using prefix if you want to use it as an absolute path or use it like this if you need a relative path.
One more advantage of StringJoiner is the fluent API it offers which means you can write code in one line. For example, the above code can be re-written as following using fluent methods of StringJoiner:
String result= new StringJoiner("/").add("usr").add("local").add("bin");
This will print:
"usr/local/bin"
If you are interested in other Java 8 features then you can also see the What's New in Java 8 course on Pluralsight, one of the clearest and concise online courses to learn Java 8. Btw, you would need a Pluralsight membership to access this course, Alternative, you can also use their 10-day-free-trial to join this course for FREE.
Joining String using join() method in Java 8
The problem with StringJoiner is that you need to know that there is a StringJoiner class which is not too bad but what if you can directly join the String from much popular java.lang.String class itself? Well, that's what Java designers thought and they have added a static join() method to join the String right from the String class itself.here is an example of using String.join() method to join multiple String literals in Java:
String colonSeparatedValue = String.join(":", "abc", "bcd", "def"); System.out.println("colon separated String : " + colonSeparatedValue);
This will print the following String:
colon separated String : abc:bcd:def
Which is quite good because now you don't need to worry about not adding delimiter at the start or removing it from the end, one of the common problems you face while manually joining multiple String together in a loop separated by a delimiter as shown earlier in my example of generating CSV String in Java.
Another advantage of String.join() method is that you can now directly convert a list of String into a CSV String in Java, without writing any manual code, here is an example of how to do it.
List mylist = Arrays.asList("London", "Paris", "NewYork"); String joined = String.join("||", mylist); System.out.println("Joined String : " + joined);
This will print the following String:
Joined String : London||Paris||NewYork
That's cool, isn't it? Now you are free from converting a list of String or set of String to a CSV String manually in Java. It's also worth noting that String.join() internally uses StringJoiner class for joining String literals. See The Complete Java MasterClass course on Udemy learn more about this and many such goodies from Java 8 and other higher Java versions.
2 Ways to Join String in Java 8
Here are 2 ways to join String in Java 8, the first example uses StringJoiner class while the second example uses String.join() method, a static utility method added on java.lang.String on JDK 8.package test; import java.util.Arrays; import java.util.List; import java.util.StringJoiner; /** * Java program to show how to join String in Java 8. * There are two ways to do that in Java 8, by using StringJoiner or * by using join() method of String class. * @author Javin */ public class Test { public static void main(String args[]) { // StringJoiner can join multiple String using any delimiter // Let's create a CSV String by joining Stirng using comma StringJoiner joiner = new StringJoiner(","); joiner.add("one"); joiner.add("two"); joiner.add("three"); System.out.println("Comma separated String : " + joiner.toString()); // You can combine all three lines into one because // StringJoiner provides a fluent interface StringJoiner delimitedString = new StringJoiner("|").add("id").add("name"); System.out.println("Pipe delimited String : " + delimitedString); // 2nd Example: You can also join String by String.join() method // By far, this is the most convenient method to join Strings // in Java. String csv = String.join(":", "abc", "bcd", "def"); System.out.println("colon separated String : " + csv); // You can even use String.join() method to join contents of // ArrayList, Array, LinkedList or any collection, actually // any container which implements Iterable interface List mylist = Arrays.asList("London", "Paris", "NewYork"); String joined = String.join("||", mylist); System.out.println("Joined String : " + joined); } } Output Comma separated String : one,two,three Pipe delimited String : id|name colon separated String : abc:bcd:def Joined String : London||Paris||NewYork
That's all about 2 ways to join String in Java 8. Now, you can finally join the String in Java 8 without using a third-party library and you also have options to use the class which makes sense for you. In general, join() method of String class is more convenient because you can directly call and pass both delimeter and individual String objects which need to be joined.
I mean, you don't need to create another object like StringJoiner. It also allows you to join String from a Collection class like ArrayList or LinkedList, which means you can create a comma-separated String from an ArrayList of String, how cool is that?
Related Java 8 Tutorials
If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8- 5 Books to Learn Java 8 from Scratch (books)
- 5 Online Course to Learn Java 8 better (courses)
- What is the default method in Java 8? (example)
- How to use Stream class in Java 8 (tutorial)
- How to convert Stream to List and Map in Java 8 (tutorial)
- How to sort the map by keys in Java 8? (example)
- How to use filter() method in Java 8 (tutorial)
- 20 Examples of Date and Time in Java 8 (tutorial)
- How to convert List to Map in Java 8 (solution)
- Difference between abstract class and interface in Java 8? (answer)
- How to format/parse the date with LocalDateTime in Java 8? (tutorial)
- How to use peek() method in Java 8 (example)
- How to sort the may by values in Java 8? (example)
- 5 Free Courses to learn Java 8 and 9 (courses)
P.S.: If you just want to learn more about new features in Java 8 then please see the course What's New in Java 8. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API and other miscellaneous changes
No comments :
Post a Comment