2015-03-02 93 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