gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:55:25 25 4
gpt4 key购买 nike

列表(lst):[the,quick,brown,fox,jumped,over,the,lazy,dog]

我正在尝试返回最短单词的集合。(dog、fox、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;
}

最佳答案

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

从文档中,比较方法必须返回

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

关于java - 迭代字符串列表以获得最短的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com