Reputation: 3500
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()));
Upvotes: 3
Views: 2330
Reputation: 271735
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:
Upvotes: 4
Reputation: 328619
If you call:
String max = Collections.max(dateStrings);
You will get the maximum string in the collection, using the natural order of strings. In other words, it will be the largest in lexicographical order. So if the list contains "aa", "bb", zz", "cc", max will be "zz".
Your example wants to retrieve the longest string in the list. So you need to provide a custom comparator that will compare the strings based on their length.
Upvotes: 0