[英]How do I iterate through a list of Strings to change the last letter of each word toUpperCase?
[英]Iterate through a list of strings to get shortest word?
列表(第一名):[快速,棕色,狐狸,跳過,越過,懶惰,狗]
我正在嘗試返回最短單詞的集合。(狗,狐狸,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;
}
我通過掃描文本文檔來完成此工作,但是我必須先將其轉換為列表,以刪除不必要的標點符號和數字。 但是我犯了一個錯誤,所以現在我需要遍歷列表而不是文件。
這是我的舊邏輯:
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;
}
使用帶有自定義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);
}
}
從文檔中,compare方法必須返回
作為第一個參數小於,等於或大於第二個參數的負整數,零或正整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.