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
*/