List
➠ Stream
➠ StringBuilder
➠ String
One solution is to convert your List
into a Stream
. Then collect the elements of that stream into a StringBuilder
. The StringBuilder
class offers an appendCodePoint
method specifically to accommodate code point integer numbers. When the mutable StringBuilder
is complete, convert to an immutable String
.
String output = codePoints.stream().collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append ).toString();
Or different formatting:
String output =
codePoints
.stream()
.collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append )
.toString();
Here is some example code.
String input = "dog" ;
List < Integer > codePoints = input.codePoints().boxed().collect( Collectors.toList() ); // In Java 16+, replace the last part with simply `.toList()`.
String output =
codePoints
.stream()
.collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append )
.toString();
See this code run live at IdeOne.com.
input: dog
codePoints: [100, 111, 103, 128054]
output: dog
To understand how that code with StringBuilder
method references works, see Java 8 Int Stream collect with StringBuilder.
We could make a utility method of this code, for convenience. For safety, we could add a call to .filter
to skip any invalid code point number (either negative or beyond Character.MAX_CODE_POINT
).
public static final String listOfCodePointsToString( List< Integer > codePoints )
{
String output =
codePoints
.stream()
.filter( codePoint -> Character.isValidCodePoint( codePoint ) )
.collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append )
.toString();
return output ;
}
See that code run live at IdeOne.com.