Wednesday, 22 June 2016

10 Examples of Joining String in Java 8 - StringJoiner and String.join()

It's quite common in day to day programming to join Strings e.g. if you have an array or List of String let's say {Sony, Apple, Google} and you want to join them by comma to produce another String "Sony, Apple, Google", there is not an easy way to do it in Java. You need to iterate through array or list and then use a StringBuilder to append a comma after each element and finally to remove the last comma because you don't want a comma after the last element. A JavaScript-like Array.join() method or join() method of Android's TextUtils class is what you need in this situation, but you won't find any of such method on String, StringBuffer, StringBuilder, Arrays, or Collections class until Java 8. Now, you have a class called StringJoiner which allows you to join multiple String by a delimiter.
Read more »

No comments:

Post a Comment