Search code examples
javajava-8java-streamjava-9java-16

How to convert a given string to an immutable list of characters in java? [Updated]


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!


Solution

  • 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:

    1. 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.

    2. 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()'