Home > Enterprise >  Finding the longest word ArrayList /Java
Finding the longest word ArrayList /Java

Time:01-02

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


}

}

CodePudding user response:

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]

CodePudding user response:

azro is right. You can figure out the problem using two iteration. I m not sure but the code below works

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

for (int i = 0; i < wordsList.size(); i  ) {
    if (wordsList.get(index).length() == wordsList.get(i).length()) {
        System.out.println("More than one longest word");
        break;
    }
}

CodePudding user response:

You can do this with one loop iteration. Storing the longest word(s) as you go.

import java.util.*;

public class Test {
    public static void main(String[] args) {
        final Collection<String> words = Arrays.asList(
                "december", "california", "cat",
                "implementation", "incrementation");

        final Collection<String> longestWords = findLongestWords(words);

        if (longestWords.size() == 1) {
            System.out.printf("The longest word is: %s\n", longestWords.iterator().next());
        } else if (longestWords.size() > 1) {
            System.out.printf("More than one longest word. The longest words are: %s\n", longestWords);
        }
    }

    private static final Collection<String> findLongestWords(final Collection<String> words) {
        // using a Set, so that duplicate words are stored only once.
        final Set<String> longestWords = new HashSet<>();

        // remember the current length of the longest word
        int lengthOfLongestWord = Integer.MIN_VALUE;

        // iterate over all the words
        for (final String word : words) {
            // the length of this word is longer than the previously though longest word. clear the list and update the longest length.
            if (word.length() > lengthOfLongestWord) {
                lengthOfLongestWord = word.length();
                longestWords.clear();
            }

            // the length of this word is currently though to be the longest word, add it to the Set.
            if (word.length() == lengthOfLongestWord) {
                longestWords.add(word);
            }
        }

        // return an unmodifiable Set containing the longest word(s)
        return Collections.unmodifiableSet(longestWords);
    }
}

CodePudding user response:

My two cents to make it done in the single loop. Can be improved further.

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

    String result;
    int length = Integer.MIN_VALUE;
    Map<String,String> map = new HashMap<>();

    for(String word: wordsList){

        if(word.length() >= length) {
            length = word.length();

            if (map.containsKey(String.valueOf(word.length())) || map.containsKey( "X"   word.length())) {
                map.remove(String.valueOf(word.length()));
                map.put("X"   word.length(), word);
            } else {
                map.put(String.valueOf(word.length()), word);
            }

        }
    }

     result = map.get(String.valueOf(length)) == null ? "More than one longest word" :
             map.get(String.valueOf(length))   " is the longest word";

    System.out.println(result);

CodePudding user response:

I changed your code to suggest a different approach to the problem. Honestly, I hope you'll find it fascinating and helpful. There are two different fashion of it, one that doesn't care about finding more than one longest word (it stamps just the first one - but you can change it as you prefer), and the other one that does.

First solution:

`

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

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


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

        wordsList.stream()
            .max(LongestWord::compare)
            .ifPresent(a -> System.out.println(a.toUpperCase()   " is the longest word with length of: "   a.length()));

}

    private static int compare(String a1, String a2) {
        if (a1.length() > a2.length())
            return 1;
        else if (a1.length() == a2.length())
            return 0;
        return -1;
    }

}

`

Second solution:

`

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


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

        int max_length = wordsList.stream()
                .max(LongestWord::compare)
                .map(String::length).orElse(0);

        List<String> finalWordsList = wordsList.stream()
                .filter(word -> word.length() == max_length)
                .collect(Collectors.toList());

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

    }

    private static int compare(String a1, String a2) {
        if (a1.length() > a2.length())
            return 1;
        else if (a1.length() == a2.length())
            return 0;
        return -1;
    }

}

`

  • Related