w3resource
Java Programming Exercies

Java Exercises: Find all of the longest word in a given dictionary

Java Basic: Exercise-138 with Solution

Write a Java program to find all of the longest word in a given dictionary.

Example-1:
{
"cat",
"flag",
"green",
"country",
"w3resource"
}
Result: "w3resource"
Example-1:
{
"cat",
"dog",
"red",
"is",
"am"
}
Result: "cat", "dog", "red"

Pictorial Presentation:

Java Basic Exercises: Find all of the longest word in a given dictionary.

Sample Solution:

Java Code:

import java.util.*;
public class Solution {
    static ArrayList<String> longestWords(String[] dictionary) {
        ArrayList<String> list = new ArrayList<String>();
        int longest_length = 0;
        for (String str : dictionary) {
            int length = str.length();
            if (length > longest_length) {
                longest_length = length;
                list.clear();
            }
            if (length == longest_length) {
                list.add(str);
            }
        }
        return list;
    }
    
public static void main(String[] args) {
		//String [] dict = {"cat", "flag", "green", "country", "w3resource"};
		String [] dict = {"cat", "dog", "red", "is", "am"};
		System.out.println("Original dictionary : "+Arrays.toString(dict));
		System.out.println("Longest word(s) of the above dictionary: "+longestWords(dict));
	}		
}

Sample Output:

Original dictionary : [cat, dog, red, is, am]
Longest word(s) of the above dictionary: [cat, dog, red]

Flowchart:

Flowchart: Java exercises: Find possible unique paths considering some obstacles, from top-left corner to bottom-right corner of a specified grid.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find possible unique paths from top-left corner to bottom-right corner of a given grid (m x n).
Next: Write a Java program to get the index of the first number and the last number of a subarray where the sum of numbers is zero from a given array of integers.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming