简体   繁体   English

遍历字符串列表以获取最短单词?

[英]Iterate through a list of strings to get shortest word?

The list(lst): [the, quick, brown, fox, jumped, over, the, lazy, dog] 列表(第一名):[快速,棕色,狐狸,跳过,越过,懒惰,狗]

I'm trying to return a collection of the shortest words.(dog, fox, the) 我正在尝试返回最短单词的集合。(狗,狐狸,the)

public Collection<String> getShortestWords() {

    ArrayList<String> newlist = new ArrayList<String>();


    for(int i = 0; i < lst.size(); i++){
        if(lst.get(i).length() > lst.get(i+1).length()){
            newlist.add(lst.get(i+1));
        }



    }return newlist;
}

I had this working by scanning the text document but I have to convert it to a list first to remove unnecessary punctuation and numbers. 我通过扫描文本文档来完成此工作,但是我必须先将其转换为列表,以删除不必要的标点符号和数字。 But I made a mistake so Now I need to iterate through a list instead of a file. 但是我犯了一个错误,所以现在我需要遍历列表而不是文件。

This is my old logic: 这是我的旧逻辑:

String shortestWord = null;
String current;
while (scan.hasNext()) {    //while there is a next word in the text
        current = scan.next();  //set current to the next word in the text
        if (shortestWord == null) { //if shortestWord is null
            shortestWord = current; //set shortestWord to current
            lst.add(shortestWord);  //add the shortest word to the array
        }
        if (current.length() < shortestWord.length()) { //if the current word length is less than previous shortest word
            shortestWord = current; //set shortest word to the current
            lst.clear();    //clear the previous array
            lst.add(shortestWord);  //add the new shortest word
        }
        else if(current.length() == shortestWord.length()){ //if the current word is the same length as the previous shortest word
            if(!lst.contains(current))

            lst.add(current);

            }
        }
        return lst;
}

Get the length of the shortest word using Collections.min with a custom Comparator then add each object to your result list when length is equals to lowest. 使用带有自定义Comparator的Collections.min获取最短单词的长度,然后在长度等于最小长度时将每个对象添加到结果列表中。

int minLength = Collections.min(yourListOfString, new Comparator<String>() {
                       @Override
                       public int compare(String arg0, String arg1) {
                           return arg0.length() - arg1.length();
                       }
                 }).length();

for(String s : yourListOfString)
{
    if(s.length() == minLength)
    {
       if(!yourResultList.contains(s))
           yourResultList.add(s);
    }
}

From the doc, the compare method must return 从文档中,compare方法必须返回

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 作为第一个参数小于,等于或大于第二个参数的负整数,零或正整数。

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

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