Convert stream to String
The opposite of converting a string to a stream, this example will demonstrate converting a java 8 stream into a string. A Collector is a reduction operation which will gather together elements from a stream into a cumulative result of a String. Collectors.joining() will return a Collector that will concatenates the input elements into a String which has similar behavior to joining strings. If you want to join the string by a delimiter just pass in a CharSequence into the joining method. For instance, if you want to join string by a comma it would look like Collectors.joining(«,») .
Java 8
@Test public void stream_to_list() String streamToString = Stream.of("a", "b", "c") .collect(Collectors.joining()); assertEquals("abc", streamToString); >
If you prefer, you could use a static import.
. import static java.util.stream.Collectors.toSet; . @Test public void stream_to_set() String streamToString = Stream.of("a", "b", "c") .collect(joining()); assertEquals("abc", streamToString); >
Convert stream to String posted by Justin Musgrove on 10 July 2014
Tagged: java and java-stream
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
Interface Stream
A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream :
int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum();
In this example, widgets is a Collection
In addition to Stream , which is a stream of object references, there are primitive specializations for IntStream , LongStream , and DoubleStream , all of which are referred to as «streams» and conform to the characteristics and restrictions described here.
To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate) ), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer) ). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.
A stream implementation is permitted significant latitude in optimizing the computation of the result. For example, a stream implementation is free to elide operations (or entire stages) from a stream pipeline — and therefore elide invocation of behavioral parameters — if it can prove that it would not affect the result of the computation. This means that side-effects of behavioral parameters may not always be executed and should not be relied upon, unless otherwise specified (such as by the terminal operations forEach and forEachOrdered ). (For a specific example of such an optimization, see the API note documented on the count() operation. For more detail, see the side-effects section of the stream package documentation.)
Collections and streams, while bearing some superficial similarities, have different goals. Collections are primarily concerned with the efficient management of, and access to, their elements. By contrast, streams do not provide a means to directly access or manipulate their elements, and are instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source. However, if the provided stream operations do not offer the desired functionality, the BaseStream.iterator() and BaseStream.spliterator() operations can be used to perform a controlled traversal.
A stream pipeline, like the «widgets» example above, can be viewed as a query on the stream source. Unless the source was explicitly designed for concurrent modification (such as a ConcurrentHashMap ), unpredictable or erroneous behavior may result from modifying the stream source while it is being queried.
- must be non-interfering (they do not modify the stream source); and
- in most cases must be stateless (their result should not depend on any state that might change during execution of the stream pipeline).
Such parameters are always instances of a functional interface such as Function , and are often lambda expressions or method references. Unless otherwise specified these parameters must be non-null.
A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, «forked» streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. However, since some stream operations may return their receiver rather than a new stream object, it may not be possible to detect reuse in all cases.
Streams have a BaseStream.close() method and implement AutoCloseable . Operating on a stream after it has been closed will throw IllegalStateException . Most stream instances do not actually need to be closed after use, as they are backed by collections, arrays, or generating functions, which require no special resource management. Generally, only streams whose source is an IO channel, such as those returned by Files.lines(Path) , will require closing. If a stream does require closing, it must be opened as a resource within a try-with-resources statement or similar control structure to ensure that it is closed promptly after its operations have completed.
Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. Streams are created with an initial choice of sequential or parallel execution. (For example, Collection.stream() creates a sequential stream, and Collection.parallelStream() creates a parallel one.) This choice of execution mode may be modified by the BaseStream.sequential() or BaseStream.parallel() methods, and may be queried with the BaseStream.isParallel() method.