- Join or Concatenate Strings with Comma in Java
- В Java 8 можно объединять строки
- Java String join() Method – 8 Practical Examples
- 2. Joining String Array Elements
- 3. Joining Multiple Array Elements
- 4. Joining StringBuffer, StringBuilder and Strings
- 5. Joining List Elements
- 6. Joining Set Elements
- 7. Joining Queue Elements
- 8. Joining Stack Elements
- Conclusion
- References:
Join or Concatenate Strings with Comma in Java
This tutorial contains Java examples to join or concatenate a string array to produce a single string using comma delimiter where items will be separated by a given separator. This code can be used to convert an array to a comma-separated string in Java.
We may need this information many times during development especially while parsing contents of the JSON or XML files.
1. Java 8 – Using String.join()
The String.join() method has two overloaded forms.
- The first version joins multiple string literals provided as var-args.
- The second version joins the strings provided in a list or an array.
Note that if an element is null, then «null» is added to the joined string.
static String join(CharSequence delimiter, CharSequence. elements) static String join(CharSequence delimiter, Iterable elements)
This method takes all strings in var-args format and all strings are passed as arguments in the method. The return string is received by appending all strings delimited by an argument delimiter .
This method can join multiple string literals that are not yet in the form of a collection or array.
String joinedString = String.join(",", "How", "To", "Do", "In", "Java"); //How,To,Do,In,Java
1.2. Joining Array or List of Strings
We can use this method to join the string items in the array to produce a joined string.
String[] strArray = < "How", "To", "Do", "In", "Java" >; String joinedString = String.join(",", strArray); //How,To,Do,In,Java
2. Java 8 – Using StringJoiner for Formatted Output
Using StringJoiner class, we can produce formatted output of joined strings. This is specially useful while using lambda collectors.
The constructors take three arguments – delimiter [mandatory], and optionally prefix and suffix .
StringJoiner(CharSequence delimiter) StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Run the example with similar input as above example to join multiple strings. We want to format the output as [How, To, Do, In, Java] then we can use the below code:
StringJoiner joiner = new StringJoiner("," ,"[", "]"); String joinedString = joiner.add("How") .add("To") .add("Do") .add("In") .add("Java") .toString(); System.out.println(joinedString); //[How,To,Do,In,Java]
3. Java 8 – Using Collectors.joining() for Streams
While using lambda expressions, we can use Collectors.joining() to collect the list items into a String.
List tokens = Arrays.asList("How", "To", "Do", "In", "Java"); String joinedString = tokens.stream() .collect(Collectors.joining(",", "[", "]")); System.out.println(joinedString); //[How,To,Do,In,Java]
4. Apache Commons – Using StringUtils.join()
The StringUtils class of the Apache Commons Langs library has several join() methods that can be used to combine an array or list of strings into a single string.
org.apache.commons commons-lang3 3.12.0
- In the first example, we are joining a string array with an empty delimiter.
- In the second example, we are joining a string array with a comma delimiter.
String[] strArray = < "How", "To", "Do", "In", "Java" >; String joinedString = StringUtils.join(strArray); System.out.println(joinedString); //HowToDoInJava String joinedString2 = StringUtils.join(strArray, ","); System.out.println(joinedString2); //How,To,Do,In,Java
Use the above-given examples to concatenate strings with comma or any other delimiter in Java.
В Java 8 можно объединять строки
Я уверен, что вы были в ситуации, в которой хотели объединять несколько строк. Если вы писали не на Java, то вероятно вы использовали функцию join() предоставленную вам самим языком программирования. Если вы писали на Java, то не могли этого сделать по простой причине — этого метода не было. Стандартная библиотека классов в Java предоставляла вам инструменты для создания приложений с графическим интерфейсом, для доступа к базам данных, для отправки данных по сети, для XML преобразований или для вызова методов сторонних библиотек. Простой метод для соединения коллекции строк не был включен. Для этого вам необходима была одна из множества сторонних библиотек. К счастью, этому пришел конец! В Java 8 мы, наконец, можем объединять строки! В Java 8 добавлен новый класс, называемый StringJoiner . Как следует из названия, мы можем использовать этот класс, чтобы объединять строки:
StringJoiner joiner = new StringJoiner(","); joiner.add("foo"); joiner.add("bar"); joiner.add("baz"); String joined = joiner.toString(); // "foo,bar,baz" // add() calls can be chained joined = new StringJoiner("-") .add("foo") .add("bar") .add("baz") .toString(); // "foo-bar-baz"
// join(CharSequence delimiter, CharSequence. elements) String joined = String.join("/", "2014", "10", "28" ); // "2014/10/28" // join(CharSequence delimiter, Iterable elements) List list = Arrays.asList("foo", "bar", "baz"); joined = String.join(";", list); // «foo;bar;baz"
List list = Arrays.asList( new Person("John", "Smith"), new Person("Anna", "Martinez"), new Person("Paul", "Watson ") ); String joinedFirstNames = list.stream() .map(Person::getFirstName) .collect(Collectors.joining(", ")); // "John, Anna, Paul»
Таким образом, нам действительно больше не нужны сторонние библиотеки для объединения строк! Оригинал статьи
Java String join() Method – 8 Practical Examples
The join() method accepts variable arguments, so we can easily use it to join multiple strings.
jshell> String.join(",", "A", "B", "C"); $1 ==> "A,B,C"
2. Joining String Array Elements
jshell> String[] fruits = < "Apple", "Banana", "Orange" >; fruits ==> String[3] < "Apple", "Banana", "Orange" >jshell> String.join(",", fruits); $3 ==> "Apple,Banana,Orange"
3. Joining Multiple Array Elements
We can also join multiple array elements to form a new string using the join() method.
String[] capitalLetters = ; String[] smallLetters = ; String result = String.join("|", String.join("|", capitalLetters), String.join("|", smallLetters));
4. Joining StringBuffer, StringBuilder and Strings
The join() method accepts CharSequence objects. So we can pass StringBuilder, StringBuffer, and Strings as an argument for this method.
jshell> StringBuffer sb1 = new StringBuffer("ABC"); sb1 ==> ABC jshell> StringBuffer sb2 = new StringBuffer("123"); sb2 ==> 123 jshell> StringBuilder sb3 = new StringBuilder("XYZ"); sb3 ==> XYZ jshell> StringBuilder sb4 = new StringBuilder("987"); sb4 ==> 987 jshell> String result = String.join(" ", sb1, sb2, sb3, sb4); result ==> "ABC 123 XYZ 987"
5. Joining List Elements
jshell> List vowelsList = List.of("a", "e", "i", "o", "u"); vowelsList ==> [a, e, i, o, u] jshell> String vowels = String.join(" ", vowelsList); vowels ==> "a e i o u"
6. Joining Set Elements
package net.javastring.strings; import java.util.HashSet; import java.util.Set; public class JavaStringJoin < public static void main(String[] args) < SetsetStrings = new HashSet<>(); setStrings.add("A"); setStrings.add(new StringBuilder("B")); setStrings.add(new StringBuffer("C")); String result = String.join("$$", setStrings); System.out.println(result); > >
Output: A$$B$$C
7. Joining Queue Elements
package net.javastring.strings; import java.util.PriorityQueue; import java.util.Queue; public class JavaStringJoin < public static void main(String[] args) < QueuemessagesQueue = new PriorityQueue<>(); messagesQueue.add("Hello"); messagesQueue.add("Hi"); messagesQueue.add("Bonjour"); String messagesCSV = String.join(",", messagesQueue); System.out.println(messagesCSV); > >
Output: Bonjour,Hi,Hello
8. Joining Stack Elements
Stack currencyStack = new Stack<>(); currencyStack.add("USD"); currencyStack.add("INR"); currencyStack.add("GBP"); String currenciesCSV = String.join(",", currencyStack); System.out.println(currenciesCSV);
Output: USD,INR,GBP
Conclusion
Java String join() is a great utility method to add array elements or iterable elements to form a new string. This has removed the need to write our custom code for this functionality.