Ishan
Ishan

Reputation: 191

find the frequency of elements in a java array

I have an int array:

{1,2,4,2,3,5,6,4,3}

How can I find frequencies of array elements like 1=1,2=2,3=2,4=4... I need a class which I can pass my array to and return an array which gives the count of array elements. ex:- array{[0]=1,[1]=2,[2]=3,[3]=4..} (for above example array);

Upvotes: 4

Views: 70624

Answers (11)

Pawan
Pawan

Reputation: 6

package practice.learning;

import java.util.Arrays;
public class FreqElem {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] names= {"Pawan","Rohan","Sudesh","Pawan","Shiv"};

        for(int i=0;i<names.length;i++) {
            int count=0;
            //System.out.print(names[i]);
            String a=names[i];
            for(int j=0;j<names.length;j++) {
                if(names[j]==a) {
                    count+=1;
                }
                
                
            }
            System.out.println(names[i]+":"+count); 
        }
        
    }

}

Output: Pawan:2 Rohan:1 Sudesh:1 Pawan:2 Shiv:1

Upvotes: 0

Ashlin Karkada
Ashlin Karkada

Reputation: 1410

Map<Integer, Integer> map = new HashMap<>();
int arr[] = new int[]{2, 2, 3, 3, 4, 5, 6, 7, 9, 9, 0, 4, 2};

for (int i = 0; i < arr.length; i++) {
    Integer count = map.getOrDefault(arr[i], 0);
    map.put(arr[i], count + 1);
}

//Print the map to see the occurrence
map.forEach((key, value) -> {
    System.out.println(key + " -> " + value);
});

Upvotes: 0

Apoorv Gupta
Apoorv Gupta

Reputation: 65

You can compute the frequency of each element in a HashMap<Element,Frequency>.

Map<Integer,Integer> h = new HashMap<>();
int arr[] = new int[]{2,2,3,3,5,6,7,9,9,0};

for(int elem:arr) {
  h.merge(elem, 1, Integer::sum);
}

Hashmap.merge() lets you specify how to update the value in the hashmap. If there is no existing value for elem, it will be similar to h.put(elem, 1). If there is an existing value, called oldFreq, it will replace it with Integer.sum(oldFreq, 1)

Upvotes: 1

Ankit Sharma
Ankit Sharma

Reputation: 1654

Using Java-8 we can find the frequency of an array in a single line.

Map<Integer, Long> freq = Arrays.stream(a).boxed().
                          collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Also, since the question demands we need to return an array

public Object[] getFrequencies(int[] a) {
    Map<Integer, Long> freq = Arrays.stream(a).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    return freq.entrySet().toArray();
}

Upvotes: 3

user3216114
user3216114

Reputation: 325

import java.util.*;
class Findfreqarray
{
    public static void main(String args[])
    {
        int t, i, j, len, count=0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of elements to insert in an array: ");
        len = in.nextInt();
        int[] arr = new int[len];
        System.out.println("Enter elements to insert in an array: ");
        for(i=0;i<len;i++)
        {
            t = in.nextInt();
            arr[i] = t;
        }
        System.out.println("\n");
        for(i=0;i<len;i++)
        {
            count=1;
            for(j=i+1;j<=len-1;j++)
            {
                if(arr[i]==arr[j] && arr[i]!='\0')
                {
                    count++;
                    arr[j] = '\0';
                }
            }
            if(arr[i]!='\0')
            {
                System.out.println(arr[i] + " is " + count + " times.\n");
            }
        }        
    }
}

Upvotes: 2

Hengameh
Hengameh

Reputation: 902

If range of the elements of the array is specified and limited to array size, the best solution is using hash map. T(n) = O(n), auxiliary space = O(n).

public static void findCount3(int[] a){
    Map<Integer, Integer> hm = new HashMap<Integer, Integer>();     
    for(int i = 0; i < a.length; i++){
            if(!hm.containsKey(a[i])){
               hm.put(a[i], 1);
            }else{
               hm.put(a[i], hm.get(a[i])+1);
    }               
    System.out.println(hm);         
}

Upvotes: 2

ankit
ankit

Reputation: 1529

class MapTest
{
    public static void main(String args[]){
        HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
        int arr[] = new int[]{2,2,3,3,5,6,7,9,9,0};
        for(int i=0; i<arr.length; i++){
            if(h.containsKey(arr[i])){
                h.put(arr[i], h.get(arr[i]) + 1);
            } else {
                h.put(arr[i], 1);
            }
        }
        System.out.println(h);
    }
}

Upvotes: 8

Masood_mj
Masood_mj

Reputation: 1184

In Java 8 you can do this

Map<Integer, Long> freq = Arrays.stream(array).boxed().
                collect(Collectors.groupingBy(Integer::intValue, Collectors.counting()));

Upvotes: 6

user1241779
user1241779

Reputation:

I have a solution for count the frequency of elements in a java array

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class ItemCount {

public static void main(String[] args)
{
    try{
            int count=1,index=1;
            BufferedReader  br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter the Size of array : ");
            int size=Integer.parseInt(br.readLine());
            System.out.print("Enter the Elements of array : ");
            int arr[]=new int[size];

            for(int i=0;i<arr.length;i++)
            {
                System.out.print("arr["+i+"] :  ");
                arr[i]=Integer.parseInt(br.readLine());
            }
            System.out.print("Sorted Array is :");
            SortingArray.sortDescendind(arr);

            for(int i=0;i<arr.length;i++)
            {
                System.out.println("arr["+i+"] :  "+arr[i]);

            }

            for(int i=0;i<arr.length;)
            {
                count=1;
                for(index=i+1;index<arr.length;index++)
                {
                    if(arr[i]==arr[index])
                    {
                        count++;
                    }
                    else{

                        break;
                    }


                }
                System.out.println(""+arr[i] +"----> "+count);
                i+=count;

            }

    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

}

/// you can select any sorting method for array---->SortingArray.sortDescendind(arr)

Upvotes: 1

Richard Chassereau
Richard Chassereau

Reputation: 468

Without giving it away here is a good starting point:

int[] array = {1,2,4,2,3,5,6,4,3};

        public int[] (array){
            //need to perform a sort...or a search
            //after searching check for matches,
            //sorting could make performing comparisons more efficient
            //not all searches/sorts are created equal.

            int[array.length] result += {"["+numberChecked+"]="+freqOccurred};
            return result;
        }

This code is has not been compiled so think of it more as psuedocode. The purpose is to get you thinking about how to achieve the desired goal. An java package may already exist that can check the frequency elements in an array, but this is what you are most likely looking for. Good Luck.

Upvotes: 1

Makoto
Makoto

Reputation: 106430

You have to do a few things:

  1. Define an upper and lower bound for your range of numbers.
  2. Establish a convenient object/data structure to store occurrences of these numbers.
  3. Iterate through the passed-in array and count all occurrences of each number, storing the result in the convenient object/data structure.

If this is done in a simple manner, it could be only a matter of reading the elements from the passed-in array and printing out the final result.

Upvotes: 3

Related Questions