Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get min and max String of list

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?

like image 715
principal-ideal-domain Avatar asked Oct 19 '25 15:10

principal-ideal-domain


1 Answers

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.

like image 83
Tunaki Avatar answered Oct 21 '25 04:10

Tunaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!