2015-03-02 57 views
0

列表(LST):对,快速,棕色,狐狸,跳下,结束了,,懒惰,狗]遍历字符串列表以获取最短的单词?

我试图返回的最短字集合(犬,狐的。 )

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

因此,将您的while循环更改为列表中的每个字符串。您不会使用'current',而是使用for循环中的变量集。 – gtgaxiola 2015-03-02 18:37:33

回答

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,比较方法必须返回

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

+0

谢谢,但这似乎在我的新列表中添加了一个额外的“the”。 – FatFockFrank 2015-03-02 18:44:08

+0

如果您不想添加重复项,只需检查它。看我的编辑。 – 2015-03-02 18:44:40

+0

谢谢一堆。 – FatFockFrank 2015-03-02 18:47:09