Find the line with the most lowercase letters from the <String> list. (Using streams)

I did 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 you can make this easier \ shoter, right?

+5
source share
2 answers

There are convenient static methods in the Comparator interface that can help you make the code shorter:

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

Lighter / shorter in taste, but you can write it that way.

 import static java.util.stream.Collectors.*; List<String> maxOfLowercase = strList.stream() .collect(groupingBy(s -> s.replaceAll("[^az]", "").length(), TreeMap::new, toList())) .lastEntry().getValue(); 

One of the advantages is that it will give you a few words if they have the same number of lowercase characters. This will filter each word once rather than once for comparison.

If you want to support all lowercase characters, you can use regex

 "[^\\p{javaLowerCase}]" 
0
source

All Articles