Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mode value in java

Tags:

java

Any know how can I get the mode value from an array? For example, if I have a array with difference number, how can I use Java to search out which number is appears the most?

like image 923
Jin Yong Avatar asked Dec 13 '22 04:12

Jin Yong


2 Answers

Completes in O(n) as opposed to O(n^2). Requires arrays of length > 0.

public static int getMode(int[] values) {
  HashMap<Integer,Integer> freqs = new HashMap<Integer,Integer>();

  for (int val : values) {
    Integer freq = freqs.get(val);
    freqs.put(val, (freq == null ? 1 : freq+1));
  }

  int mode = 0;
  int maxFreq = 0;

  for (Map.Entry<Integer,Integer> entry : freqs.entrySet()) {
    int freq = entry.getValue();
    if (freq > maxFreq) {
      maxFreq = freq;
      mode = entry.getKey();
    }
  }

  return mode;
}
like image 140
Chadwick Avatar answered Jan 02 '23 05:01

Chadwick


This is a little out there, and I don't know about it's performance, but if you were willing to try a little Groovy with your Java...

static int modal( ArrayList values ) {
    use(Collections){
        values.max{ values.frequency(it) } 
    }
}
like image 40
Kevin Williams Avatar answered Jan 02 '23 04:01

Kevin Williams