I have ended up with one of the approach below in order to convert a given string into an immutable list of characters.
Here, I have used some utility methods as follows:
- chars() method available from java 9 onwards which will convert the given string to int stream.
- mapToObj() is an intermediate operation which will convert the int stream to char stream.
- toList() is a utility method available from java 16 onwards it will collect the stream to a list which is immutable
in nature.
The code snippet shown as below:
public class Test {
public static void main(String[] args) {
String str = "helloworld";
List<Character> list = str.chars().mapToObj(x -> (char)x).toList();
System.out.println(list);
}
}
Output: [h, e, l, l, o, w, o, r, l, d]
Note :
As the list is immutable in nature, if we try to modify the list(add/remove operation), will get an exception as below:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
Bonus Points:
During this problem, I have found the difference between
Stream.collect(Collectors.toList()) and Stream.toList() i.e.
Stream.collect(Collectors.toList()) : It will collect the data
in a mutable list.
Stream.toList() : It will collect the data in an
immutable list.
The Sonarlint in IDE will also check if there is no operation
related with the modification of the list, it will prompt with a
suggestion to
Replace the usage of 'Stream.collect(Collectors.toList())'
with 'Stream.toList()'