Member-only story
Modern Java Methods for Processing Text With Streams and Lambdas
Java API offers many convenient methods for functional transformations of strings. The powerful text-related API has not changed since Java 12.

The stream API is probably the most convenient or at least elegant feature of Java. The chained stream-based code tends to be shorter and more legible than the equivalent code with for
-loops. Unfortunately that is true only if the code inside the lambdas cannot throw a checked exception, the most annoying feature of Java.
Processing text, for example converting documents into more structured records stored in a database, is quite convenient with Java. Streams and method accepting functional interfaces can further simplify the code. In this post I want to review all the string-related methods that return or receive objects belonging to java.util.stream
or java.util.function
packages. In Java 19 API I counted 21 method. Half of them have existed since Java 8 and the most novel method was introduced in Java 12. None of the methods is indispensable, they are rather convenience methods allowing to simplify Java code.
Collectors
I start from Collector
s because they are used in several other examples.
Collectors
have three methods joining()
, joining(CharSequence)
, joining(CharSequence, CharSequence, CharSequence)
returning Collector<CharSequence,?,String>
s that concatenate the strings in a stream. The resulting string can be prepended and appended with the specified prefix and suffix, and the source strings can be separated by the specified separator:
var strs = List.of("one", "two", "three");
String s1 = strs.stream().collect(Collectors.joining());
// onetwothree
String s2 = strs.stream().collect(Collectors.joining("\t"));
// one two three
String s3 = strs.stream().collect(Collectors.joining(",", "{", "}"));
// {one,two,three}
String
The most recent method among all the methods described in this post is R transform(Function<? super String,? extends R>)
. It was added in Java 12. I do not know how it could be useful.