Convert String to List Java
This post will discuss how to convert a string to a list of characters in Java. Show 1. Naive solutionA naive solution is to create a new list and add elements to it using a for-each loop, as shown below:
DownloadRun Code Output:
DownloadRun Code Output: 2. Using Java 9We can call the chars() method on a string in Java 9 and above, which returns an IntStream. Then we convert IntStream to Stream of Character using a lambda expression and collect the Stream to a new list using a Collector.
DownloadRun Code Output:
DownloadRun Code Output: 3. Using AbstractList InterfaceTo create an immutable list backed by the string, we can implement the AbstractList interface.
DownloadRun Code Output: 4. Using Guava LibraryAnother plausible way of converting a string to a list of Character is using some third-party library. Guavas Chars class provides several static utility methods pertaining to char primitives. One such method is asList(), which returns a fixed-size list backed by the array of char primitives.
Download Code Output:
Download Code Output: Thats all about converting a String to a List of Character in Java. |