2011-11-02 78 views
0

我需要获取对象的arrayList中最频繁出现的元素的计数。我有这个代码,它的工作。ArrayList中的重复元素(java)

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; 
} 

我需要知道是否有最佳方法来做到这一点。谢谢。

+2

您的代码不符合您的描述。这听起来像你需要得到最频繁发生的'valor'值 - 这是这种情况吗? –

+0

是的,对不起,我很难用英语表达这一点。是最频繁的。例如具有(0)(0)(0)(1)(1)的5个对象。你得到3. – ramons03

回答

5

典型的方法是使用一个地图,其中的关键将是“勇气”值,并且该值将是该值已出现多少次的运行计数。

+0

谢谢戴夫,我会尝试。 – ramons03

0

示例使用地图:

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()); 
} 
+0

谢谢Bhesh。这看起来好多了。 – ramons03