Skip to content
Advertisement

Java-get most common element in a list

Does Java or Guava have something that will return most common element in a list?

JavaScript

[1,3,4,3,4,3,2,3,3,3,3,3]

return 3

Advertisement

Answer

This is fairly easy to implement yourself:

JavaScript

JavaScript
3

If you want to handle cases where there’s more then one most frequent element, you can scan the list once to determine how many times the most frequent element(s) occur, and then scan the list again, put those elements in a set and return that.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement