如何从给定列表中获取包含更多小写字符的字符串?

时间:2018-11-09 10:56:41

标签: java while-loop java-stream

如何从给定的List<String>中获取带有更多小写字符的字符串?

我已经使用Java 10 Streams以一种功能性的方式来完成它,但是我想使用while循环以一种迭代的方式来做到这一点。但是我不知道该怎么做。 这是我的功能代码。

public static Optional<String> stringSearched (List<String> pl) {
   return pl.stream()
            .max(Comparator.comparing(x->x.chars()
                                       .filter(Character::iLowerCase)
                                       .count()
            ));
}

3 个答案:

答案 0 :(得分:2)

import java.util.ArrayList;
import java.util.List;

public class Something {
    public static void main(String []args){
        ArrayList<String> list = new ArrayList<String>();
        list.add("LOSER");
        list.add("wInner");
        list.add("sECONDpLACE");

        System.out.println(findMoreLowerCase(list));
    }

    private static String findMoreLowerCase(final List<String> list){
        String moreLowerCase = ""; // Tracks the current string with less lowercase
        int nrOfLowerCase=0; // Tracks the nr of lowercase for that string

        int current; // Used in the for loop
        for(String word: list){
            current = countLowerCase(word);
            if(current > nrOfLowerCase){
                // Found a string with more lowercase, update
                nrOfLowerCase = current;
                moreLowerCase = word;
            }
        }
        return moreLowerCase;
    }

    private static int countLowerCase(String s){
        // Scroll each character and count 
        int result = 0;
        for (char letter : s.toCharArray()) {
            if (Character.isLowerCase(letter)){
                ++result;
            };
        }
        return result;
    }

}

答案 1 :(得分:0)

最简单的方法是遍历所有单词,并用空字符串替换非小写字母(使用[^ a-z]等正则表达式),然后获取字符串的长度。

最长的字符串是小写字母最多的字符串。

答案 2 :(得分:0)

private String moreLowerCase(final List<String> stringList) {
  String moreLowerCase = "";
  final Iterator<String> iterator = stringList.iterator();

  while (iterator.hasNext()) {
    final String current = iterator.next().replaceAll("[^a-z]", "");
    if (current.length() > moreLowerCase.length())
      moreLowerCase = current;
    }
return moreLowerCase;
}
相关问题