我过去一直在阅读有关Java 8的内容,我知道它支持流,但我还没有对它进行过那么多的研究.
我想知道我的代码在Java 8中有多清晰.
我有以下内容:
public static float ratioNumbers(final String input) {
int countNumbers = 0;
for (char c : input.toCharArray()) {
countNumbers += (c >= '0' && c <= '9') ? 1 : 0;
}
return countNumbers * 1.0f / input.length();
}
Run Code Online (Sandbox Code Playgroud)
写这个最简洁的方法是什么?仍然保持适当的意图.
我想这样做:
public static float ratioNumbers(final String input) {
return input.chars().filter(c -> Character.isDigit(c)).count()/(float)input.length();
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用正则表达式删除所有非数字字符,而不是使用流:
public static float ratioNumbers(final String input) {
return input.replaceAll("[^\\d.]", "").length()* 1.0f/input.length();
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
long numberOfDigits = input.codePoints().filter(Character::isDigit).count();
return 1f * numberOfDigits / input.length();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |