How to Get Longest Word in Sentence in Java

The challenge

When given a string of space-separated words, return the word with the longest length.

If there are multiple words with the longest length, return the last instance of the word with the longest length.

Example:

'red white blue' // returns string value of white 'red blue gold' // returns gold
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

public class Solution { public static String longestWord(String wordString) { String longest = ""; for (String word: wordString.split(" ")) if (word.length()>=longest.length()) longest = word; return longest; } }
Code language: Java (java)

Option 2:

import java.util.Arrays; public class Solution { public static String longestWord(String words) { return Arrays.stream(words.split(" ")) .reduce((x, y) -> x.length() <= y.length() ? y : x).get(); } }
Code language: Java (java)

Option 3:

import java.util.*; public class Solution { public static String longestWord(String wordString) { final String [] ary = wordString.split(" "); Arrays.sort(ary, (a,b) -> a.length() >= b.length() ? -1 : 1); return ary[0]; } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class ExampleSolutionTests { @Test public void tests() { assertEquals("fgh", Solution.longestWord("a b c d e fgh")); assertEquals("three", Solution.longestWord("one two three")); assertEquals("grey", Solution.longestWord("red blue grey")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments