I'll explain you two methods, but won't code it for you. The most basic is using imperative programming and a loop. One could also use a custom function with max
.
Using a loop
The main idea of imperatively getting an element with the max count is having a loop in which we calculate the count we are interested in for each element. We also have a storage variable for the currently highest element and the currently highest count. Something like max_count
and max_element
. These two are coupled (which is, why the imperative method is not the best method to use, but the one I think most beginners use; you easily forget to update either one of the two and have an error).
The max_count
holds the maximum count we saw up to the current iteration, the max_element
the object which gave us the currently maximum value. If in one iteration, we see a count higher than max_count
, we update both max_count
and max_element
, so that in all upcoming iterations we know the currently highest count and element.
At the end of the loop, max_element
will be the result.
Using max
A cleaner way to read your code would be to use the Collections.max
function with a custom comparison. Usually, one learns comparing elements with the built-in comparison at first. Like when you sort a list of numbers, the numerical value is being used. When you sort strings, the alphabet is used. But you can also use custom comparators in Java (e.g. for sort
or max
). This custom comparator then retrieves two elements to compare. Instead of relying on a built-in function (which in Java would be converting the object to string representation (toString()
) and comparing alphabetically, I think), you pass it an object with only one method which calculates the loudness for both singers and compares the numbers. See this example, where employees are compared by their salary. It resembles your problem a lot, only that you will need to have a calculation for the number of uppercase letters too.