Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Letfar Avatar asked Jun 05 '15 18:06

Letfar


1 Answers

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();
like image 145
Tagir Valeev Avatar answered Oct 16 '22 14:10

Tagir Valeev