Converting String to Stream of chars

1. Overview

Java 8 introduced the Stream API, with functional-like operations for processing sequences. If you want to read more about it, have a look at this article.

In this quick article, we’ll see how to convert a String to a Stream of single characters.

2. Conversion Using chars()

The String API has a new method – chars() – with which we can obtain an instance of Stream from a String object. This simple API returns an instance of IntStream from the input String.

Simply put, IntStream contains an integer representation of the characters from the String object:

String testString = "String";
IntStream intStream = testString.chars();

It’s possible to work with the integer representation of the characters without converting them to their Character equivalent. This can lead to some minor performance gains, as there will be no need to box each integer into a Character object.

However, if we’re to display the characters for reading, we need to convert the integers to the human-friendly Character form:

Stream<Character> characterStream = testString.chars()
  .mapToObj(c -> (char) c);

3. Conversion Using codePoints()

Alternatively, we can use the codePoints() method to get an instance of IntStream from a String. The advantage of using this API is that Unicode supplementary characters can be handled effectively.

Supplementary characters are represented by Unicode surrogate pairs and will be merged into a single codepoint. This way we can correctly process (and display) any Unicode symbol:

IntStream intStream1 = testString.codePoints();

We need to map the returned IntStream to Stream<Character> to display it to users:

Stream&lt;Character&gt; characterStream2 
  = testString.codePoints().mapToObj(c -&gt; (char) c);

4. Conversion to a Stream of Single Character Strings

So far, we’ve been able to get a Stream of characters; what if we want a Stream of single character Strings instead?

Just as specified earlier in the article, we’ll use either the codePoints() or chars() methods to obtain an instance of IntStream that we can now map to Stream<String>.

The mapping process involves converting the integer values to their respective character equivalents first.

Then we can use String.valueOf() or Character.toString() to convert the characters to a String object:

Stream&lt;String&gt; stringStream = testString.codePoints()
  .mapToObj(c -&gt; String.valueOf((char) c));

5. Conclusion

In this quick tutorial, we learn to obtain a stream of Character from a String object by either calling codePoints() or chars() methods.

This allows us to take full advantage of the Stream API – to conveniently and effectively manipulate characters.

As always, code snippets can be found over on GitHub.

Related posts:

Servlet 3 Async Support with Spring MVC and Spring Security
Java Program to Find the Longest Path in a DAG
Concurrent Test Execution in Spring 5
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
An Introduction to ThreadLocal in Java
Java Program to Implement Weight Balanced Tree
Setting a Request Timeout for a Spring REST API
Java Program to Implement Sorted Singly Linked List
Java Program to Perform Addition Operation Using Bitwise Operators
Registration – Password Strength and Rules
Spring 5 Testing with @EnabledIf Annotation
LinkedHashSet trong Java hoạt động như thế nào?
Java Program to Implement Max-Flow Min-Cut Theorem
Adding Parameters to HttpClient Requests
Java Program to Implement Segment Tree
Java Program to Perform LU Decomposition of any Matrix
Python String expandtabs()
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
An Intro to Spring Cloud Contract
Extract links from an HTML page
Java Program to Check whether Graph is a Bipartite using DFS
Java Program to Implement AttributeList API
Spring Boot - Tracing Micro Service Logs
Java Program to Describe the Representation of Graph using Incidence List
Hướng dẫn Java Design Pattern – Dependency Injection
So sánh Array và ArrayList trong Java
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Spring Boot: Customize the Jackson ObjectMapper
A Guide to JUnit 5
How To Serialize and Deserialize Enums with Jackson
Spring Boot with Multiple SQL Import Files
Java Program to Implement Max Heap