迭代字符串列表以获得最短的单词?

时间:2015-03-02 18:31:13

标签: java list

清单(上):[快,棕,狐,跳,过,懒,狗]

我正在尝试返回最短词的集合。(狗,狐狸,)

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;
}

我通过扫描文本文档来完成此工作,但我必须先将其转换为列表以删除不必要的标点符号和数字。但我犯了一个错误,所以现在我需要遍历列表而不是文件。

这是我原来的逻辑:

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;
}

1 个答案:

答案 0 :(得分:2)

使用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);
    }
}

从doc中,compare方法必须返回

  

作为第一个参数的负整数,零或正整数   小于,等于或大于第二个。

相关问题