Pages

Tuesday, February 19, 2019

Java 9 String chars() method example - Internal Implementation

Java String chars():


chars method is introduced in package java.lang.String class from Java 9 onwards. This method returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.


Java String chars() method example



Syntax:

public IntStream chars​()


This method returns IntStream which holds of characters of input string and will have some light performance penalty.


Refer the article How to convert String to char before java 8.

String chars() method Example:

package examples.java.w3schools.string;

import java.util.stream.IntStream;

public class StringCharsExample {
 public static void main(String[] args) {

   IntStream stream = "world".chars();
  stream.mapToObj(i -> (char) i).forEach(System.out::println);

  }
}


Output:
w
o
r
l
d


Here I obtain an IntStream and map it to an object via the lambda i -> (char)i, this will automatically box it into a Stream<Character>, and then we can do what we want, and still use method references as a plus.

Be aware though that you must do mapToObj, if you forget and use map, then nothing will complain, but you will still end up with an IntStream, and you might be left off wondering why it prints the integer values instead of the strings representing the characters.

Other alternative way to use chars() method:


By remaining in an IntStream and wanting to print them ultimately, you cannot use method references anymore for printing:


"world".chars().forEach(i -> System.out.println((char)i));

Internal Implementation:


The below code is chars method internal implementation.


@Override
    public IntStream chars() {

        return StreamSupport.intStream(
            isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
                       : new StringUTF16.CharsSpliterator(value, Spliterator.IMMUTABLE), false);
    }


This is a overridden method from its parent class CharSequence.

Please post your questions in comment section.

No comments:

Post a Comment

Please do not add any spam links in the comments section.