Is there anything worth learning about the strman java project of 1.3k star on GitHub? Source visual to analyze a wave

Time:2021-12-30

Hello, I’m silent Wang Er.

Many students who are beginners in programming often give me a Tucao, saying, “brother, when you knock the code, will you have such a feeling, make complaints about writing, and feel that the code you write is like shit?”

I have to say here that when I first entered the “Jianghu”, I really felt that my code was badly written, but after so many years, this feeling has disappeared.

(blow, I can too, ha ha)

So, how can we make the written code not so bad?

One of my experiences is “taking doctrine”, trying not to build wheels repeatedly. Using those verified and high-quality open source libraries can not only make our code elegant, but also let us learn the essence of programming in the process of continuous use.

During the Westernization Movement, there was a very loud slogan called “learn from the foreigners and develop skills to control them”. Use it first and then learn it. It will naturally become awesome. Students, you say, is that right?

The open source library I recommend today is called strman Java. GitHub superscript 1.3k is a great string processing tool library. It is based on Java 8 and has a very concise syntax.

Next, let’s see how to use it.

Maven project only needs to be in POM Add the following dependencies to the XML file.

<dependency>
    <groupId>com.shekhargulati</groupId>
    <artifactId>strman</artifactId>
    <version>0.4.0</version>
</dependency>

Well, you can call the API of strman Java recklessly. I will insert some introduction of the source code during the introduction, so as to facilitate the students to further study and try to “know what it is and why”.

Is there anything worth learning about the strman java project of 1.3k star on GitHub? Source visual to analyze a wave

01、append

Adds a variable string parameter to the end of the specified string.

Strman. Append ("Shen", "Mo", "Wang", "II");

The results are as follows:

Silent King II

The corresponding method of append is prepend. The variable string parameter is prefixed to the specified string. The usage method is as follows.

Strman. Prepend ("Shen", "Mo", "Wang", "II");

The results are as follows:

King Mo Erchen

02、appendArray

Adds an array of strings to the end of the specified string.

String [] STRs = {"silent", "King", "two"};
Strman. Appendarray ("sink", STRs);

The results are as follows:

Silent King II

Appendarray is actually called inside append. Let’s take a look at the source code:

public static String append(final String value, final String... appends) {
    return appendArray(value, appends);
}

When using variable parameters, you actually create an array whose size is the number of variable parameters, then put the parameters into the array, and then pass the array to the called method

You can see by looking at the decompiled bytecode.

Strman. Append ("Shen", "Mo", "Wang", "II");

Actually equivalent to:

Strman. Append ("Shen", new string [] {"Mo", "Wang", "Er"});

Let’s take another look at the source code of the appendarray method:

public static String appendArray(final String value, final String[] appends) {
    StringJoiner joiner = new StringJoiner("");
    for (String append : appends) {
        joiner.add(append);
    }
    return value + joiner.toString();
}

Stringjoiner for internal use, a new class in Java 8. There are two construction methods.

First, specify the separator:

public StringJoiner(CharSequence delimiter) {
    this(delimiter, "", "");
}

Second, specify separator, prefix and suffix:

public StringJoiner(CharSequence delimiter,
                    CharSequence prefix,
                    CharSequence suffix) {
    this.prefix = prefix.toString();
    this.delimiter = delimiter.toString();
    this.suffix = suffix.toString();
}

Although you can attach a separator after each string with the help of the StringBuilder class, stringjoiner provides a simpler way to implement it without writing a lot of code.

03、at

Gets the character at the specified index.

Strman. At ("silent King II", 0);
Strman. At ("silent King II", - 1);
Strman. At ("silent King II", 4);

The results are as follows:

Optional [sink]
Optional [II]
Optional.empty

That is, at can handle-(length-1)reach(length-1)The index within (when the index is negative, it will be searched from the end). If it exceeds this range, it will be returnedOptional.emptyTo avoid null pointers.

Take a look at the source code:

public static Optional<String> at(final String value, int index) {
    if (isNullOrEmpty(value)) {
        return Optional.empty();
    }
    int length = value.length();
    if (index < 0) {
        index = length + index;
    }
    return (index < length && index >= 0) ? Optional.of(String.valueOf(value.charAt(index))) : Optional.empty();
}

In essence, it is through the string classcharAt()Method, but wrapped with a layer of optional, it skillfully avoids the annoying null pointer.

Optional is a new class in Java 8. This class provides a class level solution for representing optional values rather than empty references.

Is there anything worth learning about the strman java project of 1.3k star on GitHub? Source visual to analyze a wave

04、between

Returns an array of strings according to the specified start and end characters.

String [] results = Strman. Between ("[silent King II] [an interesting programmer]," [","]);
System.out.println(Arrays.toString(results));

The results are as follows:

[silent King II, an interesting programmer]

Take a look at the source code:

public static String[] between(final String value, final String start, final String end) {
    String[] parts = value.split(end);
    return Arrays.stream(parts).map(subPart -> subPart.substring(subPart.indexOf(start) + start.length()))
            .toArray(String[]::new);
}

java.util.ArraysClass is a special tool class for arrays. Basically, common operations on arrays are considered in the arrays class,stream()Method to convert an array to a stream:

String [] intro = new string [] {"Shen", "silent", "King", "two"};
Arrays.stream(intro);

The new stream stream in Java 8 greatly improves the productivity of developers when operating a collection. To operate a stream, you first need to have a data source, which can be an array or a collection. Each operation will return a new stream object for chain operation, but the original stream object will remain unchanged.

map()Method can convert elements in a stream into elements in a new stream, and it can receive a lambda expression as a parameter. Lambda expressions describe a code block (or anonymous method) that can be passed as a parameter to a constructor or ordinary method for subsequent execution.

Consider the following code:

() -> System. out. Println ("silent King II")

Let’s explain from left to right,()Is the parameter list of lambda expression (there are no parameters in this example),->Identify this string of code as a lambda expression (that is, see->I knew it was lambda,System. out. Println ("silent King II")For the code to be executed, print “silent King II” to the standard output stream.

toArray()Method can convert a stream into an array, which you may be curious aboutString[]::new, what is it? Take a looktoArray()Method source code.

<A> A[] toArray(IntFunction<A[]> generator);

in other wordsString[]::newIt is an intfunction, a function that can generate the required new array. You can decompile the bytecode to see what it is:

String[] strArray = (String[])list.stream().toArray((x$0) -> {
    return new String[x$0];
});

That is, it returns an array of strings of a specified length.

05、chars

Returns an array of individual characters that make up a string.

String [] results = Strman. Chars ("silent King II");
System.out.println(Arrays.toString(results));

The results are as follows:

[Shen, Mo, Wang, two]

Take a look at the source code:

public static String[] chars(final String value) {
    return value.split("");
}

The internal is through the string classsplit()Method.

06、charsCount

Counts the number of occurrences of each character in the string.

Map<Character, Long> map = Strman. Charscount ("the sister of silent King II is called silent King III");
System.out.println(map);

The results are as follows:

{de = 1, Mo = 2, three = 1, Mei = 2, Shen = 2, Jiao = 1, Wang = 2, two = 1}

Do you think this method is much more interesting in an instant? In one step, count the number of occurrences of each character in the string. Take a look at the source code.

public static Map<Character, Long> charsCount(String input) {
    return input.chars().mapToObj(c -> (char) c).collect(groupingBy(identity(), counting()));
}

String classchars()The method is new in Java 9. It returns a stream for the basic type int: intstream.

mapToObj()The method is mainly to box the elements in the stream and convert them into a value of reference type. It receives an intfunction interface, which is aint -> RFunction interface.

collect()Method can convert the flow into a set map.

07、collapseWhitespace

Replace multiple consecutive spaces with a single space.

Strman. Collapsewhitespace ("silent King II is an interesting programmer");

The results are as follows:

Strman. Collapsewhitespace ("silent King II, an interesting programmer")

Take a look at the source code:

public static String collapseWhitespace(final String value) {
    return value.trim().replaceAll("\\s\\s+", " ");
}

Internal first usetrim()Method removes the spaces on both sides, and then replaces multiple consecutive spaces with a single space with a regular expression.

08、contains

Verifies that the specified string contains a string.

System. out. Println (strman. Contains ("silent King II", "Shen");
System.out.println(Strman.contains("Abbc", "a", false));

The results are as follows:

true
true

The third parameter casesensitive is optional. If false, it indicates that it is case insensitive.

Take a look at the source code:

public static boolean contains(final String value, final String needle, final boolean caseSensitive) {
    if (caseSensitive) {
        return value.contains(needle);
    }
    return value.toLowerCase().contains(needle.toLowerCase());
}

Internal through string classcontains()Method implementation. If it is not case sensitive, it is called firsttoLowerCase()Method to lowercase.

09、containsAny

Verifies that the specified string contains any string in the string array, or more.

System. out. Println (strman. Containsany ("silent King II", new string [] {"Shen", "III"}));
System. out. Println (strman. Containsany ("silent King II", new string [] {"silent", "three"}));
System. out. Println (strman. Containsany ("silent King 2", new string [] {"no", "three"}));

The results are as follows:

true
true
false

Take a look at the source code:

public static boolean containsAny(final String value, final String[] needles, final boolean caseSensitive) {
    return Arrays.stream(needles).anyMatch(needle -> contains(value, needle, caseSensitive));
}

Stream class provides three methods for element matching:

  • anyMatch(), as long as one element matches the passed in condition, it returns true.
  • allMatch(), if only one element does not match the incoming condition, false is returned; Returns true if all match.
  • noneMatch(), as long as one element matches the incoming condition, it returns false; Returns true if all match.

10、endsWith

Verify that the string ends with a string.

System. out. Println (strman. Endswith ("silent King II", "II");
System.out.println(Strman.endsWith("Abbc", "A", false));

The results are as follows:

true
false

Take a look at the source code:

public static boolean endsWith(final String value, final String search, final int position,
                               final boolean caseSensitive) {
    int remainingLength = position - search.length();
    if (caseSensitive) {
        return value.indexOf(search, remainingLength) > -1;
    }
    return value.toLowerCase().indexOf(search.toLowerCase(), remainingLength) > -1;
}

Internal through string classindexOf()Method implementation.

11、ensureLeft

Make sure that the string starts with a string. If the string does not start with the specified string, append it.

System. out. Println (strman. Ensureleft ("silent King II", "Shen");
System. out. Println (strman. Ensureleft ("silent King II", "Shen");

The results are as follows:

Silent King II
Silent King II

Take a look at the source code:

public static String ensureLeft(final String value, final String prefix, final boolean caseSensitive) {
    if (caseSensitive) {
        return value.startsWith(prefix) ? value : prefix + value;
    }
    String _value = value.toLowerCase();
    String _prefix = prefix.toLowerCase();
    return _value.startsWith(_prefix) ? value : prefix + value;
}

Internal through string classstartsWith()Method first makes a judgment. If the result is false, it is connected through the “+” operator.

Ensureright corresponds to ensurereft. Similarly, it will not be repeated here.

12、base64Encode

Base64 encodes the string.

Strman. Base64encode ("silent King II");

The results are as follows:

5rKJ6buY546L5LqM

Base64 is a representation of binary data based on 64 printable characters. Take a look at the source code:

public static String base64Encode(final String value) {
    return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
}

The internal is implemented through the base64 class, a new class in Java 8.

The decoding method corresponding to base64encode is base64decode. The usage method is as follows:

Strman.base64Decode("5rKJ6buY546L5LqM")

If it cannot be decoded, an illegalargumentexception will be thrown.

Exception in thread "main" java.lang.IllegalArgumentException: Last unit does not have enough valid bits
    at java.base/java.util.Base64$Decoder.decode0(Base64.java:763)
    at java.base/java.util.Base64$Decoder.decode(Base64.java:535)
    at java.base/java.util.Base64$Decoder.decode(Base64.java:558)
    at strman.Strman.base64Decode(Strman.java:328)
    at com.itwanger.strman.Demo.main(Demo.java:58)

13、binEncode

Converts a string to binary Unicode (16 bits).

Strman. Binencode ("silent King II");

The results are as follows:

0110110010001001100111101101100001110011100010110100111010001100

The corresponding method of binencode is bindecode, which converts binary Unicode into string. The use method is as follows:

Strman.binDecode("0110110010001001100111101101100001110011100010110100111010001100");

14、first

Returns the first n characters of a string.

System. out. Println (strman. First ("silent King II", 0));
System. out. Println (strman. First ("silent King II", 1));
System. out. Println (strman. First ("silent King II", 2));

The results are as follows:

Optional[]
Optional [sink]
Optional [silence]

If n is negative, a stringindexoutofboundsexception exception will be thrown:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 4
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
    at java.base/java.lang.String.substring(String.java:1874)
    at strman.Strman.lambda$first$9(Strman.java:414)
    at java.base/java.util.Optional.map(Optional.java:265)
    at strman.Strman.first(Strman.java:414)
    at com.itwanger.strman.Demo.main(Demo.java:68)

For the case where n is negative, I don’t think it is handled skillfully by the previous at method.

Take a look at the source code:

public static Optional<String> first(final String value, final int n) {
    return Optional.ofNullable(value).filter(v -> !v.isEmpty()).map(v -> v.substring(0, n));
}

The internal is through the string classsubstring()Method, but it does not deal with the case where n is less than 0.

ofNullable()Method can create an optional object that can be empty or non empty.

filter()The parameter type of the method is predict (a new functional interface in Java 8), that is, a lambda expression can be passed to the method as a condition. If the result of the expression is false, an empty optional object will be returned, otherwise the filtered optional object will be returned.

map()Method can convert the original optional object into a new optional object according to certain rules, and the original optional object will not be changed.

First corresponds to the last method, which returns the last n characters of the string.

15、head

Returns the first character of a string.

Strman. Head ("silent King II");

The results are as follows:

Optional [sink]

Take a look at the source code:

public static Optional<String> head(final String value) {
    return first(value, 1);
}

Internal is by callingfirst()Method, but n is 1.

16、unequal

Check whether the two strings are unequal.

Strman. Unequal ("silent King II", "silent King III");

The results are as follows:

true

Take a look at the source code:

public static boolean unequal(final String first, final String second) {
    return !Objects.equals(first, second);
}

Internal is throughObjects.equals()Method, because the string class overridesequals()Method, that is, actually through the string classequals()Method.

17、insert

Inserts a string at the specified index.

Strman. Insert ("silence II", "King", 2);

The results are as follows:

Silent King II

Take a look at the source code:

public static String insert(final String value, final String substr, final int index) {
    if (index > value.length()) {
        return value;
    }
    return append(value.substring(0, index), substr, value.substring(index));
}

If the index exceeds the length of the string, the original string is returned directly; Otherwise, callappend()Method inserts the specified string into the corresponding index.

18、repeat

Repeats the string a specified number of times.

Strman. Repeat ("silent King II", 3);

The results are as follows:

Silence King II silence King II silence King II

Take a look at the source code:

public static String repeat(final String value, final int multiplier) {
    return Stream.generate(() -> value).limit(multiplier).collect(joining());
}

Stream.generate()The generated stream is serial (relative to parallel) but disordered (relative to ordered) by default. Since it is infinite, in the pipeline, operations such as limit must be used to limit the size of the stream.

collect(joining())You can convert to a string.

19、leftPad

Returns a new string of the given length to populate the beginning of the string.

Strman. Leftpad ("Wang Er", "Silence", 6);

The results are as follows:

Silent King II

Take a look at the source code:

public static String leftPad(final String value, final String pad, final int length) {
    if (value.length() > length) {
        return value;
    }
    return append(repeat(pad, length - value.length()), value);
}

Internal will call firstrepeat()Method, and then callappend()Method splicing.

The leftpad method corresponds to rightpad, which fills the end of the string.

19)removeEmptyStrings, remove the empty string from the string array.

String [] results = Strman. Removeemptystrings (new string [] {"Shen", "", "", "" silent King II "});
System.out.println(Arrays.toString(results));

The results are as follows:

[Shen, silent King II]

Take a look at the source code:

public static String[] removeEmptyStrings(String[] strings) {
    if (Objects.isNull(strings)) {
        throw new IllegalArgumentException("Input array should not be null");
    }
    return Arrays.stream(strings).filter(str -> str != null && !str.trim().isEmpty()).toArray(String[]::new);
}

Through streamfilter()Method filters out spaces.

20、reverse

Invert the string.

Strman. Reverse ("silent King II");

The results are as follows:

Er Wang Mo Shen

Take a look at the source code:

public static String reverse(final String value) {
    return new StringBuilder(value).reverse().toString();
}

Internal is throughStringBuilderClassreverse()Method.

21、safeTruncate

Truncate the string without breaking the integrity of the word.

Strman.safeTruncate("Java is the best",13,"...");

The results are as follows:

Java is...

Take a look at the source code:

public static String safeTruncate(final String value, final int length, final String filler) {
    if (length == 0) {
        return "";
    }
    if (length >= value.length()) {
        return value;
    }

    String[] words = words(value);
    StringJoiner result = new StringJoiner(" ");
    int spaceCount = 0;
    for (String word : words) {
        if (result.length() + word.length() + filler.length() + spaceCount > length) {
            break;
        } else {
            result.add(word);
            spaceCount++;
        }
    }
    return append(result.toString(), filler);
}

Call firstwords()Methods word segmentation is performed on the string, then truncated according to length, and finally called.append()Method to fill in the upper filler.

Safetruncate corresponds to truncate, which may destroy the integrity of words. The use method is as follows:

Strman.truncate("Java is the best",13,"...")

The results are as follows:

Java is th...

Take a look at the source code:

public static String truncate(final String value, final int length, final String filler) {
    if (length == 0) {
        return "";
    }
    if (length >= value.length()) {
        return value;
    }
    return append(value.substring(0, length - filler.length()), filler);
}

It is simply cutting and filling, without protecting words.

22、shuffle

Shuffle the string.

Strman. Shuffle ("silent King II");

The results are as follows:

Wang Mo Er Shen

Take a look at the source code:

public static String shuffle(final String value) {
    String[] chars = chars(value);
    Random random = new Random();
    for (int i = 0; i < chars.length; i++) {
        int r = random.nextInt(chars.length);
        String tmp = chars[i];
        chars[i] = chars[r];
        chars[r] = tmp;
    }
    return Arrays.stream(chars).collect(joining());
}

callchars()Method splits a string into a string array, then traverses it, rearranges it, and finally converts it into a new string through stream.

23. Other methods

There are many other ingenious string processing methods in strman, such as wrapping the string according to the specified prefix and suffix, surround, etc. students can refer to the official document of strman for learning:

https://github.com/shekhargul…

PS: Recently, a small partner sent a private letter to me asking for a high-quality Java Tutorial. It took me a long time to find one in GitHub, 115K star. It’s really very good. Let’s take a look at the directory:

Is there anything worth learning about the strman java project of 1.3k star on GitHub? Source visual to analyze a wave

Is there anything worth learning about the strman java project of 1.3k star on GitHub? Source visual to analyze a wave

Is there anything worth learning about the strman java project of 1.3k star on GitHub? Source visual to analyze a wave

It took me three and a half hours to organize this tutorial into a PDF. I sent it to my little partner. He sent a private letter at once. Soon, “second brother, you are too careful. The quality of this tutorial is really high. You can’t refuse!”

If you are also interested in this PDF, you can get it in the following way.

Link: https://pan.baidu.com/s/1rT0l5ynzAQLF–efyRHzQw Password: dz95

Say more, when you encounter good resources, you can learn a little and earn a little while making it eat ash, right? Knowledge is endless, but as long as we learn a little more than others, will we surpass it?

Give it a compliment, I hope more people can see it!