The 30 second answer
I use max with a comparator on string length, which returns an Optional. On ties max keeps one of them with no promise which; if they want the first longest string I use a reduce that only replaces when the new length is strictly greater.
Could you say this in an interview?
Optional<String> longest = words.stream()
.max(Comparator.comparingInt(String::length));Ties: max returns one of them; the Javadoc does not promise which. To keep the first: reduce((a, b) -> b.length() > a.length() ? b : a). [Opinion]
Sources (2)
- Stream.max / reducedocs.oracle.com
- Comparatordocs.oracle.com