Java 11: New in String

    Hello! Since the release of Java 11, 24 hours have passed and the first reviews of the release have finally begun to appear. I will devote my small article to the unnoticeable for official releases and therefore deprived of attention of updating the String class, especially since it is not mentioned in the official documentation of the 11th Java (I, in any case, did not find information about it).

    Indeed, if we take a look at the String class, then among the many familiar methods we find several marked as "@since 11" . And yes, officially in Java, they appeared only yesterday.

    Of course, there may well be doubts about the usefulness of each of the functions, since the most useful and necessary functions have already been written in previous versions of Java, but these may be useful to someone. The article came out small, but this is not only my fault, but also the fault of Oracle - they included only 4 (+2) methods in the release, which, of course, is not much.

    Let's get started

    strip ();


    This method removes all spaces before the first non-space and after the last. For example:

    String withSpaces = "     a     ";
    String withoutSpaces = withSpaces.strip();
    String OUTPUT_TEMPLATE = "<%s>"
    System.out.println(String.format(OUTPUT_TEMPLATE, withSpaces));
    System.out.println(String.format(OUTPUT_TEMPLATE, withoutSpaces));

    The result displayed will be:

    original: <     a     >
    strip: <a>

    The strip () method has two cousins ​​- stripLeading () and stripTrailing (). The first - removes spaces only in front, before the first non-space. The second is just behind.

    String leading = withSpaces.stripLeading();
    String trailing = withSpaces.stripTrailing();

    We get the result:

    stripLeading: <a     >
    stripTrailing: <     a>

    UPD.


    Here in the comments suggest that it would not hurt to see what the difference with the same trim () method, which, in fact, does the same.

    We look. The differences really are.

    publicstatic String trim(byte[] value){
            int len = value.length;
            int st = 0;
            while ((st < len) && ((value[st] & 0xff) <= ' ')) {
                st++;
            }
            while ((st < len) && ((value[len - 1] & 0xff) <= ' ')) {
                len--;
            }
            return ((st > 0) || (len < value.length)) ?
                newString(value, st, len - st) : null;
        }

    As we can see, in the old implementation, using two iterations, the index of the first non-space is calculated first, and then the index of the last non-space, and then a new line is cut from these data and returned. Just spaces are cut off, we will notice it.

    Now look at the strip () method.

    publicstatic String strip(byte[] value){
            int left = indexOfNonWhitespace(value);
            if (left == value.length) {
                return"";
            }
            int right = lastIndexOfNonWhitespace(value);
            return ((left > 0) || (right < value.length)) ? newString(value, left, right - left) : null;
        }
        publicstaticintindexOfNonWhitespace(byte[] value){
            int length = value.length;
            int left = 0;
            while (left < length) {
                char ch = (char)(value[left] & 0xff);
                if (ch != ' ' && ch != '\t' && !Character.isWhitespace(ch)) {
                    break;
                }
                left++;
            }
            return left;
        }
        publicstaticintlastIndexOfNonWhitespace(byte[] value){
            int length = value.length;
            int right = length;
            while (0 < right) {
                char ch = (char)(value[right - 1] & 0xff);
                if (ch != ' ' && ch != '\t' && !Character.isWhitespace(ch)) {
                    break;
                }
                right--;
            }
            return right;
        }

    The new method defines in general all cases when a symbol is not visible, be it a space, tab, and so on. (those who wish can climb into the jungle of the isWhiteSpace implementation).

    Thus, the new method is preferable if you want to cut off not only spaces, but in general all invisible characters.

    isBlank ();


    The method returns the result of the query whether this string is “empty”, containing no characters except spaces, tabs and other invisible characters.

    That is, if we execute this code:

    String blank = "     ";
    Boolean isBlank = blank.isBlank();

    The result will be:

    true

    Inside the method itself, there are two implementations - for Latin characters and for a string in UTF-16 encoding.

    publicbooleanisBlank(){
            return indexOfNonWhitespace() == length();
        }
        privateintindexOfNonWhitespace(){
            if (isLatin1()) {
                return StringLatin1.indexOfNonWhitespace(value);
            } else {
                return StringUTF16.indexOfNonWhitespace(value);
            }
        }

    repeat ();


    This method copies the contents of the string a specified number of times and returns the result on a single line.

    For example, by running the code:

    String sample = "(^_^) ";
    String multiple = sample.repeat(10);

    We'll get:

    (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) 

    If the number of iterations is zero, then the string will not contain characters at all.

    String blank = sample.repeat(0);

    Result:

    length: 0

    lines ();


    It would be strange to expect from Oracle that they will release the String update without including any implementation of the Stream API in the class. And they did include the functionality in the String class.

    The lines method converts all lines of a string to the corresponding Stream. It looks like this:

    String lines = "Blind Text Generator is a useful tool\n" +
                    "which provides Lorem Ipsum and a number of alternatives.\n" +
                    "The number of characters, words, and paragraphs\n" +
                    "are easily controlled and you can set \n" +
                    "the font to appreciate how it’ll look in your design.";
            lines
                    .lines()
                    .map(l -> "next line: " + l)
                    .forEach(System.out::println);

    We get the result:

    next line: Blind Text Generator is a useful tool
    next line: which provides Lorem Ipsum and a number of alternatives.
    next line: The number of characters, words, and paragraphs
    next line: are easily controlled and you can set 
    next line: the font to appreciate how it’ll look in your design.

    We received a full-fledged stream, with which we can then do everything that we usually do with regular streams. The use of this can be very different, and I would like to hope that this feature will be warmly accepted by the developers.

    If you look inside the method itself, we will see that there are two splitters to choose from to convert a string to a Stream, depending on what encoding the string is in.

    public Stream<String> lines(){
            return isLatin1() ? StringLatin1.lines(value)
                              : StringUTF16.lines(value);
        }

    The list of release innovations in the String part ends here. If I missed something, I will be glad to find out about it and add to the review. All the examples of code you can feel yourself in a resource on the githaba.

    Also popular now: