Benji Weiss
Benji Weiss

Reputation: 416

finding the shortest word in an array of strings java

im trying to write a code to take in a group of words, and return the smallest word in character length. pretty simple, for some reason its returning 'bye' when there is a shorter word in there such as 'no'.

public class function2 {

    public static void main(String [] args) {
        String [] SA = {"hello", "goodbye", "jack", "bye", "yes", "no", "yoo"};
        smallest(SA);
        System.out.println("The shortest word is " + smallest(SA));
    }

    public static String smallest(String SA[]) {
        String first = SA[0];
        for (int i = 1 ; i < SA.length ; i++) {
            if ((SA[i].compareTo(first)) < 0) {
                first = SA[i];
            } // if
        } // for
        return first;
    }// smallest
}// lab1b

Upvotes: 6

Views: 26662

Answers (6)

jpep1
jpep1

Reputation: 290

Shortest algorithm with Java 8+ using elegant Comparator.comparing method.

final String shortest = List.of("hello", "yes", "no")
                          .stream()
                          .min(Comparator.comparing(String::length))
                          .get();

Upvotes: 4

Sufiyan Ghori
Sufiyan Ghori

Reputation: 18743

In Java 8, you create a Comparator that will check the length of string which would make the array ascending, convert that list in a stream, and use sorted to sort the array, eventually, use findFirst to return the first element and get() to convert it into a String.

String[] words = new String[]{"Hello", "aadsads", "adssadsadads", "aaa"};
String shortest = Arrays.asList(words).stream()
        .sorted((e2, e1) -> e1.length() > e2.length() ? -1 : 1)
        .findFirst().get();

Upvotes: 4

Leo
Leo

Reputation: 844

Im not sure what you are trying to do with the method compareTo(), but if you want to keep find the length of a string you use the length() method.

public class function 2
{

    public static void main(String[] args) {
        String [] SA = {"hello" , "goodbye"  , "jack" , "bye" , "yes" , "no" , "yoo"};

        System.out.println("The shortest word is " + smallest(SA));
    }

    public static String smallest(String SA[]) {
        //Keep track of the shortest word by index and length
        int index = 0, minLength = SA[0].length();
        for (int i = 1; i < SA.length; i++){
            //if the next string is smaller in length then we save that index and length in our variables
            if(SA[i].length() < minLength){
                index = i;
                minLength = SA[i].length();  
            }           
        }
        //returns the smallest word
        return SA[index];
    }

}

Upvotes: 0

Chris Martin
Chris Martin

Reputation: 30736

import java.util.Comparator;
import java.util.function.Function;

import static java.util.Arrays.asList;

public class Foo {

    public static void main(String[] args) {
        String[] words =
            {"hello", "goodbye", "jack", "bye", "yes", "no", "yoo"};
        System.out.println(shortestWord(words));
    }

    static String shortestWord(String[] words) {
        return asList(words).stream().min(compareBy(String::length)).get();
    }

    static <A, B extends Comparable<B>> Comparator<A> compareBy(
            Function<A, B> f) {
        return (A x, A y) -> f.apply(x).compareTo(f.apply(y));
    }
}

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201429

Your method is close, but your variable names are a bit difficult to read to start you only need to call your method once to print the shortest name (calling it twice searches twice, and discards the first result),

public static void main(String[] args) {
    String[] SA = { "hello", "goodbye", "jack", "bye", "yes", "no", "yoo" };
    System.out.println("The shortest word is " + smallest(SA));
}

Next, it's usually a good idea to test that your input is valid (not null and at least one element). You should also decide how you want to handle those cases, I chose to return ""; below. Finally, you need to check length() the String(s) to get the shortest word. Something like,

public static String smallest(String words[]) {
    if (words == null || words.length < 1) {
        return "";
    }
    String smallest = words[0];
    for (int i = 1; i < words.length; i++) {
        if (words[i].length() < smallest.length()) {
            smallest = words[i];
        }
    }
    return smallest;
}// smallest

Upvotes: 3

Pshemo
Pshemo

Reputation: 124215

compareTo doesn't compare length of Strings, but their alphabetic order.

You should change your condition to if (SA[i].length()<first.length()).

Upvotes: 9

Related Questions