[英]Is this the best way to do this? Is there a cleaner way?
該方法按預期工作,但我想知道是否有更好的更干凈的方法使用現代Java元素編寫它。
/**
* Counts how many strings in a given list are shorter than a given min length
* @param strings
* @param minLength
* @return
*/
public int countShortStrings(List<String> strings, int minLength){
int numShort = 0;
for (String str : strings) {
if (str.length() < minLength) {
numShort++;
}
}
return numShort;
}
您可以使用Stream
:
public long countShortStrings(List<String> strings, int minLength){
return strings.stream().filter(str -> str.length() < minLength).count();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.