Created
May 15, 2023 13:29
-
-
Save dehidehidehi/c39637242f400a6cd454be6a01b5df92 to your computer and use it in GitHub Desktop.
Filters the characters of a given CharSequence based on a provided IntPredicate and a specified Charset.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Filters the characters of a given CharSequence based on a provided IntPredicate. | |
* This method is useful for removing unwanted characters from a string, such as non-alphanumeric characters. | |
* | |
* @param cs The input CharSequence to be filtered. | |
* @param characterFilter The IntPredicate to determine which characters should be kept. | |
* @return A new String containing only the characters that satisfy the characterFilter. | |
*/ | |
private String filterCharacters(final CharSequence cs, final IntPredicate characterFilter) { | |
return cs | |
.chars() | |
.filter(characterFilter) | |
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) | |
.toString(); // default Charset | |
} | |
/** | |
* Filters the characters of a given CharSequence based on a provided IntPredicate and a specified Charset. | |
* This method is useful for removing unwanted characters from a string, such as non-alphanumeric characters, | |
* while also ensuring the correct encoding is used with low over-head. | |
* | |
* @param cs The input CharSequence to be filtered. | |
* @param charset The Charset to be used for encoding the filtered characters. | |
* @param characterFilter The IntPredicate to determine which characters should be kept. | |
* @return A new String containing only the characters that satisfy the characterFilter, encoded using the specified | |
* charset. | |
*/ | |
private String filterCharacters(final CharSequence cs, final Charset charset, final IntPredicate characterFilter) { | |
final var sb = cs | |
.chars() | |
.filter(characterFilter) | |
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append); | |
// Required for specifying charset. | |
final var byteBuffer = charset.encode(CharBuffer.wrap(sb)); | |
final var encodedBytes = new byte[byteBuffer.remaining()]; | |
byteBuffer.get(encodedBytes); | |
return new String(encodedBytes); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment