How to find the largest and the smallest word in a string with Java

2 Answers

0 votes
public class FindTheLargestAndSmallestWordInString_Java {
  
    public static void main(String[] args) {
  
        String s = "java c cpp python csharp";
          
        String[] words = s.split(" ");
         
        String maxs = words[0];
        String mins = words[0];
          
        for (String w: words) {
            if (w.length() > maxs.length())
                maxs = w;
            if (w.length() < mins.length())
                mins = w;
        }
        
        System.out.println("The largest word is: " + maxs);
        System.out.println("The smallest word is: " + mins);
    }
}

    
/*
run:
   
The largest word is: python
The smallest word is: c
    
*/

 



answered Mar 20, 2017 by avibootz
edited Oct 10, 2024 by avibootz
0 votes
import java.util.Arrays;
import java.util.Comparator;

public class WordAnalyzer {

    /**
     * A lightweight, immutable data carrier record for the results (Java 16+).
     */
    public record WordResult(String largest, String smallest) {}

    /**
     * Finds the largest and smallest words in a given string.
     * 
     * @param text The input string containing words.
     * @return A WordResult record containing the largest and smallest words.
     */
    public static WordResult findLargestAndSmallestWords(String text) {
        if (text == null || text.isBlank()) {
            return new WordResult("", "");
        }

        // Split the string by one or more whitespace characters
        String[] words = text.trim().split("\\s+");

        if (words.length == 0 || (words.length == 1 && words[0].isEmpty())) {
            return new WordResult("", "");
        }

        // Use Java Streams with Comparator.comparingInt for clean, expressive extrema finding
        String largest = Arrays.stream(words)
                .max(Comparator.comparingInt(String::length))
                .orElse("");

        String smallest = Arrays.stream(words)
                .min(Comparator.comparingInt(String::length))
                .orElse("");

        return new WordResult(largest, smallest);
    }

    public static void main(String[] args) {
        String s = "Java is a high-level class-based object-oriented programming language";

        // Retrieve results from the record container
        WordResult result = findLargestAndSmallestWords(s);

        System.out.println("Largest word:  " + result.largest());
        System.out.println("Smallest word: " + result.smallest());
    }
}


/*
run:

Largest word:  object-oriented
Smallest word: a

*/

 



answered 1 day ago by avibootz
...