Java stream join 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.

Источник

Convert Java Stream to String

On this page we will learn how to convert Java Stream to String. To convert stream into string, we can use following methods.
1. Collectors.joining
2. Stream.reduce
Now let us discuss them using examples.

Contents

Using Collectors.joining

The Collectors.joining returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

public static Collector joining(CharSequence delimiter)

The Collector is passed as argument to collect method that performs a mutable reduction operation on the elements using a Collector .

 R collect(Collector collector)
package com.concretepage; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class UsingJoining < public static void main(String[] args) < //example 1 String s1 = Stream.of("A", "B", "C", "D").collect(Collectors.joining()); System.out.println(s1); //example 2 Listlist = new ArrayList<>(); list.add("Gauri"); list.add("Lakshmi"); list.add("Saraswati"); String s2 = list.stream().collect(Collectors.joining(",")); System.out.println(s2); //example 3 List cityList = Arrays.asList(new City(1, "Varanasi"), new City(2, "Prayag"), new City(3, "Ayodhya")); String s3 = cityList.stream() .map(c -> c.getName()) .collect(Collectors.joining("|")); System.out.println(s3); //example 4 String s4 = cityList.stream() .map(c -> new StringBuffer(c.getName()).append("-").append(c.getId())) .collect(Collectors.joining("|")); System.out.println(s4); > > class City < private int id; private String name; public City(int id, String name) < this.id = id; this.name = name; >//Sets and Gets >
ABCD Gauri,Lakshmi,Saraswati Varanasi|Prayag|Ayodhya Varanasi-1|Prayag-2|Ayodhya-3

Using Stream.reduce

The Stream.reduce performs a reduction on the elements of this stream, using an associative accumulation function and returns Optional .

Optional reduce(BinaryOperator accumulator)
package com.concretepage; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class UsingReduce < public static void main(String[] args) < //example 1 String s1 = Stream.of(1, 2, 3, 4).map(e ->e.toString()).reduce("", String::concat); System.out.println(s1); //example 2 List list = new ArrayList<>(); list.add("Gauri"); list.add("Lakshmi"); list.add("Saraswati"); String s2 = list.stream(). reduce((x, y) -> new StringBuffer(x).append("-").append(y).toString()).get(); System.out.println(s2); //example 3 String s3 = Stream.of(new City(1, "Varanasi"), new City(2, "Prayag"), new City(3, "Ayodhya")) .map(c -> c.getName()) .reduce((x, y) -> new StringBuffer(x).append("-").append(y).toString()).get(); System.out.println(s3); > >
1234 Gauri-Lakshmi-Saraswati Varanasi-Prayag-Ayodhya

Источник

Java 8 Streams | Collectors.joining() method with Examples

The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object. This method uses the stream to do so. There are various overloads of joining methods present in the Collector class. The class hierarchy is as follows:

java.lang.Object ↳ java.util.stream.Collectors

joining()

java.util.stream.Collectors.joining() is the most simple joining method which does not take any parameter. It returns a Collector that joins or concatenates the input streams into String in the order of their appearance.

public static Collector joining()

Illustration: Usage of joining() method

Program 1: Using joining() with an array of characters

In the below program, a character array is created in ‘ch’. Then this array is fed to be converted into Stream using Stream.of(). Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character array is joined into a String using Collectors.joining() method. It is stored in the ‘chString’ variable.

Java

Program 2: Using joining() with a list of characters

In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method. It is stored in ‘chString’ variable.

Java

Program 3: Using joining() with n list of string

In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method. It is stored in ‘chString’ variable.

Java

joining(delimiter)

java.util.stream.Collectors.joining(CharSequence delimiter) is an overload of joining() method which takes delimiter as a parameter, of the type CharSequence. A delimiter is a symbol or a CharSequence that is used to separate words from each other. For example, in every sentence, space ‘ ‘ is used as the default delimiter for the words in it. It returns a Collector that joins or concatenates the input elements into String in the order of their appearance, separated by the delimiter.

public static Collector joining(CharSequence delimiter)

Below are the illustration for how to use joining(delimiter) method:

Program 1: Using joining(delimiter) with a list of characters: In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter. It is stored in ‘chString’ variable.

Java

G, e, e, k, s, f, o, r, G, e, e, k, s

Program 2: Using joining(delimiter) with a list of string:

In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter. It is stored in ‘chString’ variable.

Java

joining(delimiter, prefix, suffix)

java.util.stream.Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) is an overload of joining() method which takes delimiter, prefix and suffix as parameter, of the type CharSequence. A delimiter is a symbol or a CharSequence that is used to separate words from each other. A prefix is a symbol or a CharSequence that is joined at the starting of the 1st element of the String. Then suffix is also a CharSequence parameter but this is joined after the last element of the string. i.e. at the end. For example, in every , space ‘ ‘ is used as the by default delimiter for the words in it. The ‘’ is the suffix. It returns a Collector that joins or concatenates the input elements into String in the order of their appearance, separated by the delimiter.

public static Collector joining(CharSequence delimiter. CharSequence prefix, CharSequence suffix))

Below are the illustration for how to use joining(delimiter, prefix, suffix) method:

Program 1: Using joining() with a list of characters: In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter, “[” as the prefix and “]” as the suffix. It is stored in ‘chString’ variable.

Источник

Читайте также:  Python socket server timeout
Оцените статью