Pacific-Design.com

    
Home Index

1. Algorithms

2. Find Frequent Number

Algorithms / Find Frequent Number /

Find the most frequent elements in an array

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class FindFrequentNumber  {

    public static void main(String[] args) {
        //List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 3));
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(3);
         
        usingHashMap(list);
    }


    public static void usingHashMap(ArrayList<Integer> list) {

        Map<Integer,Integer> hashMap = new HashMap<>();

        for (Integer tmp : list) {

            if(hashMap.containsKey(tmp)) {
                int value = hashMap.get(tmp);
                hashMap.put(tmp, value+1);
            } else {
                hashMap.put(tmp, 1);
            }
        }

        int maxKey=0;
        int maxValue=0;

        for(Map.Entry<Integer, Integer> entry : hashMap.entrySet()){

            if(entry.getValue() > maxValue){
                maxValue = entry.getValue();
                maxKey = entry.getKey();
            }
        }

        System.out.println("Frequent Key : " + maxKey + " , " + maxValue + " times occurred");

    }
}






Initalize array of integers

import java.util.HashMap;
import java.util.Map;

public class FindFrequentNumber  {
    
    static int[] input={1,2,3,4,5,5,7,8,9};

    public static void main(String[] args) {
        usingHashMap(input);
    }


    public static void usingHashMap(int[] input) {

        Map<Integer,Integer> hashMap = new HashMap<>();

        for(int i=0;i<input.length;i++){
            int tmp=input[i];

            if(hashMap.containsKey(tmp)) {
                int value  = hashMap.get(tmp);
                hashMap.put(tmp, value+1);
            } else {
                hashMap.put(tmp, 1);
            }
        }

        int maxKey=0;
        int maxValue=0;

        for(Map.Entry<Integer, Integer> entry : hashMap.entrySet()){

            if(entry.getValue() > maxValue){
                maxValue = entry.getValue();
                maxKey = entry.getKey();
            }
        }

        System.out.println("Frequent Key : " + maxKey + " , " + maxValue + " times occurred");

    }
}

References:

https://coderanch.com/t/408008/java/initializing-ArrayList