I am looking for a solution to convert a given string for example: “helloworld” to a list of characters which should be immutable in nature.
What I already tried is using StreamApi
'Stream.collect(Collectors.toList())'
however this results in a mutable list (not immutable one)
Any help appreciated!
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:
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()'