[英]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.