Is this the best way to do this? Is there a cleaner way?

John O Sullivan :

This method is working as intended but I am wondering is there a better cleaner way to write it using modern Java elements.

    /**  
     * 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;  
    }  
Eran :

You can use Streams:

public long countShortStrings(List<String> strings, int minLength){  
    return strings.stream().filter(str -> str.length() < minLength).count();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127744&siteId=1