java – How to count repeated elements in an array?

Question:

I have the following question, I have an array of integers with n elements, what I need is for the element and the number of times it is repeated to be returned in a two-dimensional array , here is an example:

  • n = 9
  • array = {1, 2, 2, 1, 1, 3, 5, 1, 2}
  • The result would be: arrayTwodimensional = { {1,4}, {2,3}, {3,1}, {5,1} }

I have the following code:

 int contador = 0;
 int[] ar = {1, 2, 2, 1, 1, 3, 5, 1, 2};
 for (int i = 0; i < ar.length; i++) {
     for (int j = 0 ; j < ar.length; j++)
         if(ar[i] == ar[j])
             contador++;
     System.out.print(contador + ",");
     contador = 0;
 }

And as a result I get the following:

4,3,3,4,4,1,1,4,3,

Which are the times that each element is repeated, only that in the previous code they are repeated. At this point I really don't know how to proceed.

Note: I know that with an ArrayList it could be solved much better, but for this time I would like it to be only with arrays.

Please, I hope you can help me with this concern.

Answer:

The best way is to use a Set , this does not allow duplicate elements

List aLista = Arrays.asList(ar);
Set<Integer> miSet = new HashSet<Integer>(aLista);
for(int s: miSet){

 System.out.println(s + " " +Collections.frequency(aLista,s));

}

You can read about Collections.frequency() , it returns an integer

And you can read about Set , which does not allow to enter two equal values

More formally, a set does not contain a pair of elements e1 and e2 such that e1.equals(e2)

Scroll to Top