ramons03
ramons03

Reputation: 307

Repeated elements in an ArrayList (java)

I need to get the count of the most frequently occurring element in an arrayList of Objects. I have this code and it´s working.

public static int contarRepeditos(ArrayList<Objecto> a) {
    int resul = 0;
    ArrayList<Integer> valores = new ArrayList<Integer>();
    for (int i = 0; i < a.size(); i++) {
        valores.add(a.get(i).getValor());
    }
    ArrayList<Integer> resultados = new ArrayList<Integer>();
    for (int i = 0; i < valores.size(); i++) {
        resultados.add(Collections.frequency(valores, a.get(i).getValor()));
    }
    resul = Collections.max(resultados);
    return resul;
}

I need to know if there are a best way to do that. Thanks.

Upvotes: 0

Views: 1826

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Example using map:

public static int contarRepeditos(List<Objecto> a) {
    Map<Integer, Integer> freqMap = new HashMap<Integer, Integer>();
    for (Objecto obj : a) {
        freqMap.put(obj.getValor(), (freqMap.get(obj.getValor()) == null ? 1 : (freqMap.get(obj.getValor()) + 1)));
    }
    return Collections.max(freqMap.values());
}

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160191

The typical method would be to use a map, where the key would be the "valor" value, and the value would be a running count of how many times that value has appeared.

Upvotes: 5

Related Questions