Java Reference
In-Depth Information
■
the
toMap()
method returns a non-concurrent map that has performance overhead when streams are
processed in parallel. It has a companion method called
toConcurrentMap()
that returns a concurrent collector that
should be used when streams are processed in parallel.
Tip
Joining Strings Using Collectors
The
joining()
method of the
Collectors
class returns a collector that concatenates the elements of a stream of
CharSequence
and returns the result as a
String
. The concatenation occurs in the encounter order. The
joining()
method is overloaded and it has three versions:
•
joining()
•
joining(CharSequence delimiter)
joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
The version with no arguments simply concatenates all elements. The second version uses a delimiter to be used
between two elements. The third version uses a delimiter, a prefix and a suffix. The prefix is added to the beginning of
the result and the suffix is added to end of the result. Listing 13-10 shows how to use the
joining()
method.
•
Listing 13-10.
Joining a Stream of CharSequence Using a Collector
// CollectJoiningTest.java
package com.jdojo.streams;
import java.util.List;
import java.util.stream.Collectors;
public class CollectJoiningTest {
public static void main(String[] args) {
List<Person> persons = Person.persons();
String names = persons.stream()
.map(Person::getName)
.collect(Collectors.joining());
String delimitedNames = persons.stream()
.map(Person::getName)
.collect(Collectors.joining(", "));
String prefixedNames = persons.stream()
.map(Person::getName)
.collect(Collectors.joining(", ", "Hello ", ". Goodbye."));
System.out.println("Joined names: " + names);
System.out.println("Joined, delimited names: " + delimitedNames);
System.out.println(prefixedNames);
}
}