简体   繁体   中英

Find the String with the largest number of lowercase letters from a List<String>. (Using streams)

I've done something like this:

List<String> strList = asList("getElementById", "htmlSpecialChars", "httpRequest");
String maxOfLowercase = strList.stream()
            .max((o1, o2) -> {
                long lowerCount1 = o1.chars().filter(Character::isLowerCase).count();
                long lowerCount2 = o2.chars().filter(Character::isLowerCase).count();
                return Long.compare(lowerCount1, lowerCount2);
            }).get();

But I think it is possible to make this more easier\\shoter, isn't it?

There are convenient static methods in Comparator interface which may help you to make the code shorter:

String maxOfLowercase = strList.stream()
        .max(Comparator.comparingLong(o -> o.chars().filter(Character::isLowerCase).count()))
        .get();

Easier/shorter is to taste but you can write it this way.

import static java.util.stream.Collectors.*;

List<String> maxOfLowercase = strList.stream()
                      .collect(groupingBy(s -> s.replaceAll("[^a-z]", "").length(),
                                                          TreeMap::new, toList()))
                      .lastEntry().getValue();

One advantage is that it will give you multiple words if they have the same number of lower cases characters. This will only filter each word once, rather than once per comparison.

If you would like to support all lower case characters you can use the regex

"[^\\p{javaLowerCase}]"

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