Skip to content
Advertisement

Finding the longest word ArrayList /Java

I want to write a method which finds the longest String (word). The output should be the longest word in case of two words with the same lenght the output should be: “More than one longest word”.

I used ArrayList and almost had a solution, but something goes wrong. The case is that I have a problem when two words have the same lenght. The output is : More than one longest word More than one longest word 14 incrementation is the longest word

Please check out piece of my code and help me to find the answer 🙂

public class LongestWord {
public static void main(String[] args) {


    ArrayList<String> wordsList = new ArrayList<String>();
    wordsList.add("december");
    wordsList.add("california");
    wordsList.add("cat");
    wordsList.add("implementation");
    wordsList.add("incrementation");


    int largestString = wordsList.get(0).length();
    int index = 0;

    for (int i = 0; i < wordsList.size(); i++) {
        if (wordsList.get(i).length() > largestString) {
            largestString = wordsList.get(i).length();
            index = i;

        }else if(wordsList.get(i).length() == largestString){
            largestString = wordsList.get(i).length();
            index = i;
            System.out.println("More than one longest word");
        }
    }
    System.out.println(largestString +" " + wordsList.get(index) +" is the longest word ");


}

}

Advertisement

Answer

The fact is that you can’t tell what the biggest word until you have iterated the whole list.

So iterate on the list

  • if word is bigger than previous largest size : clear list and save word
  • if word has same size as largest size : save word
  • if word is smaller : nothing
List<String> wordsList = Arrays.asList(
        "december", "california", "cat",
        "implementation", "incremntation");

int maxLength = Integer.MIN_VALUE;

List<String> largestStrings = new ArrayList<>();
for (String s : wordsList) {
    if (s.length() > maxLength) {
        maxLength = s.length();
        largestStrings.clear();
        largestStrings.add(s);
    } else if (s.length() == maxLength) {
        largestStrings.add(s);
    }
}

if (largestStrings.size() > 1) {
    System.out.println("More than one longest word");
    System.out.println(largestStrings);
} else {
    System.out.println(largestStrings.get(0) + " is the longest word");
}

Gives

More than one longest word
[implementation, incrementation]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement