John O Sullivan
John O Sullivan

Reputation: 301

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

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;  
    }  

Upvotes: 2

Views: 57

Answers (1)

Eran
Eran

Reputation: 393851

You can use Streams:

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

Upvotes: 5

Related Questions