Skip to content

understanding comparator in Collections.max

Can somebody please explain what the following lines of code mean?. I had a hard time understanding the Comparator part.I tried googling but all of them were too complex for me to understand. Could somebody please explain it in simpler way?

String maxLengthString = Collections.max(dateStrings, Comparator.comparing(s -> s.length()));


The max method returns the element that is considered the “biggest” in the collection.

In this case, you have a collection of strings. By default, strings are compared alphabetically. When you order strings alphabetically, the ones at the top are considered strings that has a smaller value, while the ones at the bottom are considered strings that has a larger value.

However, whoever wrote the code in your question does not want to compare strings that way. He/she wants to compare strings by their lengths. So a longer string will mean a “bigger” string.

You can pass in a second argument to max specifying how you want to compare the strings. Since you want to compare them by length, you pass in:

Comparator.comparing(s -> s.length())

Some useful things you might find helpful: