You will have problems when the elements are repeated in the list, you will have double the total of repetitions.
To use an iterative method, you could have two variables, repe
which will be the total number of repetitions of a number in the list, and k as index for the auxiliary list.
We iterate over the list, take the element and iterate in the second for where the condition apart from the typical i< n
also compares that the auxiliary list does not contain !contains
the element, because if it contains it already it means that it is a item that has already been evaluated. we avoid the iteration
At the end of the internal for we compare that the number of repetitions is greater than 0 and if so we add the element to the auxiliary list, we increase the index k
, we carry out the printing and then we reset the counter to 0
List<Integer> lista = new ArrayList<>();
lista.add(1);
lista.add(3);
lista.add(2);
lista.add(3);
lista.add(1);
lista.add(1);
int repe = 0;
int k = 0;
List<Integer> repetidos = new ArrayList<>();
for (int x = 0; x < lista.size(); x++) {
for (int y = 0; y < lista.size() && !repetidos.contains(lista.get(x)); y++) {
if (lista.get(x).equals(lista.get(y)))
repe +=1;
}
if(repe>0){
repetidos.add(k,lista.get(x));
System.out.println("EL ELEMENTO " + repetidos.get(k) + " SE REPITE "+ repe);
k++;
}
repe=0;
}
One way would be to use Stream
, using the collect to perform a reduction of the initial% lista
, will reduce it basically to a Key grouping , value that will be assigned to Map
, where the key will be the word and the value the total of repetitions, for this the method is used counting from the class Collectors
List<Integer> lista = new ArrayList<>();
lista.add(1);
lista.add(3);
lista.add(2);
lista.add(3);
lista.add(1);
lista.add(1);
Map<Integer, Long> repeticiones = lista.stream().
collect(Collectors.groupingBy(w -> w, Collectors.counting()));
for (Map.Entry<Integer, Long> entry : repeticiones.entrySet())
System.out.println("Número : " + entry.getKey()+
" , Se Repite : " + entry.getValue()+ " Veces");