Low Orbit Flux Logo 2 F

Java How To Find Mode Of An Array

Today we’re going to show you how to find the mode of an array in Java. The mode is the value that occurs most often.

Here is an example that will find the mode of an array. It works on the assumption that there is only one mode. If there is a multi modal array which contains two or more modes ( equal values ) only one of them will be given as the solution.

import java.util.*;
  
class Test1 {
    public static void main( String args[] ) {

        int []a = {10,20,30,40,50,60,71,80,90,91,
                      25,25,35,48,59,69,73,82,92,9435,
                  :    1,2,3,4,5,25,25,25};
        HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
        int max  = 1;        // frequency
        int max_value = 0;   // max value

        for(int i = 0; i < a.length; i++) {
            if (h.get(a[i]) != null) {
                int current = h.get(a[i]);
                current++;
                h.put(a[i], current);

                if(current > max) {
                    max  = current;
                    max_value = a[i];
                }
            }
            else
                h.put(a[i],1);
        }
        System.out.println(max_value);
    }
}

Multi Modal Arrays

Here is a solution for multi modal arrays:

import java.util.*;

class Test1 {
    public static void main( String args[] ) {

    int []a = {10,20,30,40,50,60,71,80,90,91,
               25,25,35,48,59,69,73,82,92,9435,
               1,2,3,4,5,25,25,25,1,1,1,1};
    HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
    int max  = 1;        // frequency
    int max_value = 0;   // max value
    final List modes = new ArrayList();


    for(int i = 0; i < a.length; i++) {
        if (h.get(a[i]) != null) {
            int current = h.get(a[i]);
            current++;
            h.put(a[i], current);

            if(current > max) {
                max  = current;
                max_value = a[i];
            }
        }

        else
            h.put(a[i],1);
    }

    for(final Map.Entry<Integer, Integer> r : h.entrySet()){
        if(r.getValue() == max)
            modes.add(r.getKey());
    }
    for(int t : modes){
        System.out.println(t);
    }


    }
}
</code></pre>