简体   繁体   中英

Iterate through a list of strings to get shortest word?

The list(lst): [the, quick, brown, fox, jumped, over, the, lazy, dog]

I'm trying to return a collection of the shortest words.(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;
}

I had this working by scanning the text document but I have to convert it to a list first to remove unnecessary punctuation and numbers. But I made a mistake so Now I need to iterate through a list instead of a file.

This is my old logic:

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

Get the length of the shortest word using Collections.min with a custom Comparator then add each object to your result list when length is equals to lowest.

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

From the doc, the compare method must return

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM