简体   繁体   中英

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

You can use Stream s:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM