简体   繁体   English

从List中查找具有最大小写字母数的String <String> 。 (使用流)

[英]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: Comparator界面中有方便的静态方法,可以帮助您缩短代码:

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}]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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