Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe