Skip to content
Advertisement

Find all strings with smallest length in an array

I want to return the smallest values from my words array

Finding the shortest word is easy but I am not sure how to return a new array with the shortest words.

public class Test{
    public static void main(String args[]){
        
        String[] words = {"What", "is", "the", "shortest", "word", "is"};
        String shortest = words[0];
        for ( int i=0; i<words.length; i++){
            if(words[i].length() <= shortest.length()){
                shortest = words[i];
            }
        }
        System.out.println(shortest);

    }
}


The expected output is something like shorestWords [] = {"is", "is"}

Advertisement

Answer

Since most of the answers are not considering that result is expected in String[] instead of ArrayList, here’s how I did it.

public static void main (String[] args) throws java.lang.Exception
{
    String[] words = {"What", "is", "the", "shortest", "word", "is", "on"};
    int countShortest = 0;
    int smallestLength = words[0].length();
    for (int i=1; i<words.length; i++){
        if(words[i].length() < smallestLength) {
            smallestLength = words[i].length();
            countShortest=0;
        }
        if(words[i].length() == smallestLength) {
            countShortest++;
        }
    }
    String result[] = new String[countShortest];
    int k = 0;
    for (int i=0; i<words.length; i++){
        if(words[i].length() == smallestLength) {
            result[k] = words[i];
            k++;
        }
    }
    for (int i=0; i<result.length; i++){
        System.out.print(result[i] + " ");
    }
    
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement