Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the most frequent value from an array

I have an array like the following

String[] football_club = {"Barcelona", "Real Madrid", "Chelsea", "Real Madrid", "Barcelona", "Barcelona"};

//result
Sting result_club = "a value most in the array"

From the array above, the "Barcelona" which has a value which often exist in the array.
How coding to find the value that appears most frequently in an array?

like image 761
ramadani Avatar asked Dec 09 '22 11:12

ramadani


1 Answers

You can make a HashMap<String,Integer>. If the String already appears in the map, increment it's key by one, otherwise, add it to the map.

For example:

put("Barcelona", 1);

Then, assume it's "Barcelona" again, you can do:

put("Barcelona", get("Barcelona") + 1);

Since the key of "Barcelona" is 1, now when you put it, the key will be 2.

like image 191
Maroun Avatar answered Dec 27 '22 12:12

Maroun