Java join string array to string

How to convert an array to a string in Java

Sometimes you want to convert an array of strings or integers into a single string. However, unfortunately, there is no direct way to perform this conversion in Java.

The default implementation of the toString() method on an array only tells us about the object’s type and hash code and returns something like [Ljava.lang.String;@f6f4d33 as output.

In this article, we shall look at different ways to convert an array into a string in Java.

The String.join() method returns a new string composed of a set of elements joined together using the specified delimiter:

String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = String.join(", ", fruits); System.out.println(str); // Apple, Orange, Mango, Banana 

You can also pass the strings that you want to join directly to the String.join() method, as shown below:

String str = String.join(" ", "Java", "is", "awesome", "🌟"); System.out.println(str); // Java is awesome 🌟 
ListString> animals = List.of("Fox", "Dog", "Loin", "Cow"); String str = String.join("-", animals); System.out.println(str); // Fox-Dog-Loin-Cow CharSequence[] vowels = "a", "e", "i", "o", "u">; String str2 = String.join(",", vowels); System.out.println(str2); // a,e,i,o,u 

Java Streams API provides the Collectors.joining() method to join strings from the Stream using a delimiter:

String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.stream(fruits).collect(Collectors.joining(", ")); System.out.println(str); // Apple, Orange, Mango, Banana 

Besides delimiter, you can also pass prefix and suffix of your choice to the Collectors.joining() method:

String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.stream(fruits) .collect(Collectors.joining(", ", "[", "]")); System.out.println(str); // [Apple, Orange, Mango, Banana] 

The Arrays.toString() method returns a string representation of the contents of the specified array. All array’s elements are joined together using a comma ( , ) as a delimiter and enclosed in square brackets ( [] ) as shown below:

String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.toString(fruits); System.out.println(str); // [Apple, Orange, Mango, Banana] 

The best thing about Arrays.toString() is that it accepts both primitive and object arrays and converts them into a string:

int[] number = 1, 2, 3, 4>; System.out.println(Arrays.toString(number)); // [1, 2, 3, 4] double[] prices = 3.46, 9.89, 4.0, 2.89>; System.out.println(Arrays.toString(prices)); // [3.46, 9.89, 4.0, 2.89] 

The StringBuilder class is used to create mutable strings in Java. It provides an append() method to append the specified string to the sequence. The toString() method of the StringBuilder class returns a string representation of the data appended. To convert an array to a string using StringBuilder , we have to use a loop to iterate over all array’s elements and then call the append() method to append them into the sequence:

String[] fruits = "Apple", "Orange", "Mango", "Banana">; StringBuilder builder = new StringBuilder(); for (int i = 0; i  fruits.length; i++)  builder.append(fruits[i]).append(" "); > String str = builder.toString(); System.out.println(str); // Apple Orange Mango Banana 
int[] number = 1, 2, 3, 4>; StringBuilder builder = new StringBuilder(); for (int i = 0; i  number.length; i++)  builder.append(number[i]).append(" "); > String str = builder.toString(); System.out.println(str); // 1 2 3 4 

The StringJoiner class was introduced in Java 8, and it provides methods for combining multiple strings into a single string using the specified delimiter:

String path = new StringJoiner("/") .add("/usr") .add("share") .add("projects") .add("java11") .add("examples").toString(); System.out.println(path); // /usr/share/projects/java11/examples 

As you can see above, the StringJoiner class provides a very fluent way of joining strings. We can easily chain multiple calls together to build a string.

Finally, the last way to convert an array of strings into a single string is the Apache Commons Lang library. The join() method of the StringUtils class from Commons Lang transforms an array of strings into a single string:

String[] names = "Atta", "Arif", "Meero", "Alex">; String str = StringUtils.join(names, "|"); System.out.println(str); // Atta|Arif|Meero|Alex 

To convert a string back into an array in Java, read this article. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

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.

Источник

Convert string array to string in java

1. String.join()
Java string class has a join() method, which accepts two arguments
a) A separator
b) An array of CharSequence interface
and returns a string with elements of array combined with the separator.

Since string implements CharSequence , it can be supplied to join() . Example,

String[] arr = < "Abc", "Def", "Ghi", "Jkl" >; String joined = String.join("", arr));

This example joins string array elements without any separator. If you want, you can supply a separator as the first argument.

join() internally loops over the array and uses Java 8 StringJoiner class(discussed next) to convert array to string.
2. Using StringJoiner
Java 8 StringJoiner is used for joining string values using its add() method.
To convert a string array to string, it can be utilized as below

String[] arr = < "Abc", "Def", "Ghi", "Jkl">; StringJoiner joiner = new StringJoiner(""); for (String string : arr) < joiner.add(string); >System.out.println(joiner);

Constructor of StringJoiner accepts a string, which acts as a delimiter pr separator between joined strings.
So, if you want to join strings with comma as a separator, then provide it as constructor argument.
3. Java streams
Java 8 streams can be used to convert a string array to string as shown below

String[] arr = ; String join = Arrays. stream(arr). collect(Collectors.joining());
  1. To get the stream over array elements, stream() method is used.
  2. collect() method is a terminal operation used to combine stream elements, with the help of a collector.
  3. To get the collector, Collectors.joining() method is used.
    joining() joins the stream elements in to a string and returns a collector object.

This method will concatenate any null elements to the resultant string.
To avoid null elements, use stream filter() method as shown below.

Arrays. stream(arr). filter(s -> s != null). collect(Collectors.joining());
String[] arr = ; String join = Joiner.on("").join(arr); System.out.print(join);

If there is a null string in the array, then this method will raise a NullPointerException .

To avoid this, add a skipNulls() method before join() , so that it will ignore any null elements.

String[] arr = ; String join = Joiner.on("").skipNulls().join(arr);

Add below dependency for this library

// MAVEN com.google.guava guava 31.1-jre  // GRADLE implementation 'com.google.guava:guava:31.1-jre'

5. Apache Commons Lang

String join = StringUtils.join(arr); System.out.println(join);

join() automatically converts null to an empty string.

Following dependency needs to be added for this library

// MAVEN org.apache.commons commons-lang3 3.12.0  // GRADLE implementation 'org.apache.commons:commons-lang3:3.12.0'

6. Using StringBuffer
Iterate over the array with a for loop and add elements to a StringBuffer with its append() method as shown below

StringBuffer buffer = new StringBuffer(); for (String string : arr)

  • Remove duplicate characters from a String in 5 ways
  • Remove last character from a string in java
  • Convert character to String in java in 2 ways
  • Convert string to int in java in 3 ways
  • Convert int to string in java
  • Convert string to float in java in 3 ways
  • Convert string to double in java in 4 ways
  • split string example
  • Substring with example
  • Check if string contains another string
  • Convert char array to String in java
  • Convert byte array to String in Java
  • Java compare strings in 7 ways
  • Java generate random string
  • Reverse string using stack in java
  • Convert each alternate character of a string to upper case in java
  • Add character to string in java
  • Check for palindrome string in java
  • Print strings on different lines with line separator in java
  • Iterate through string in java
  • Print name 10 times in java
  • Convert string array to string in java
  • Validate UUID string in java
  • String interpolation in java
  • Check for non-alphanumeric characters in a string

Источник

Читайте также:  Путь до директории java
Оцените статью