I've got a List<String> list
and want to get the first and last String of that list in alphabetical order. I want to solve that problem using the power of Java 8 and Streams with collectors.
This does not work:
String first = list.stream().collect(Collectors.minBy(String.CASE_INSENSITIVE_ORDER));
It gives me a compiler error:
Type mismatch: cannot convert from Optional to String
Can you explain why and show me the best way to do what I want to do?
Collectors.minBy
and Collectors.maxBy
return an Optional
: if the Stream is empty, an empty Optional
is returned; otherwise, an Optional
containing the result is returned.
If you want to have a default value (or just null
) when the Stream is empty, you can call orElse
.
String first = list.stream().collect(minBy(String.CASE_INSENSITIVE_ORDER)).orElse(null);
Also, if you're sure the Stream is not empty, you can directly call get()
and retrieve the value.
As a side-note, you can also return the minimum value by calling Collections.min
(resp. Collections.max
):
String first = Collections.min(list, String.CASE_INSENSITIVE_ORDER);
without the need of creating a Stream pipeline. Note that this will throw an exception if the list is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With