ArrayList中的重复元素(java)
我需要获得对象arrayList中最频繁出现的元素的计数。我有这个代码,它正在工作ArrayList中的重复元素(java),java,arraylist,Java,Arraylist,我需要获得对象arrayList中最频繁出现的元素的计数。我有这个代码,它正在工作 public static int contarRepeditos(ArrayList<Objecto> a) { int resul = 0; ArrayList<Integer> valores = new ArrayList<Integer>(); for (int i = 0; i < a.size(); i++) { va
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;
}
public static int contarRepeditos(数组列表a){
int result=0;
ArrayList valores=新的ArrayList();
对于(int i=0;i
我需要知道是否有最好的方法。谢谢。典型的方法是使用映射,其中键是“valor”值,该值是该值出现多少次的运行计数。典型的方法是使用映射,其中键是“valor”值,该值将是该值出现次数的运行计数。使用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());
}
public static int contarRepeditos(列表a){
Map freqMap=newhashmap();
(反对对象:a){
freqMap.put(obj.getValor(),(freqMap.get(obj.getValor())==null?1:(freqMap.get(obj.getValor())+1));
}
返回Collections.max(freqMap.values());
}
使用地图的示例:
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());
}
public static int contarRepeditos(列表a){
Map freqMap=newhashmap();
(反对对象:a){
freqMap.put(obj.getValor(),(freqMap.get(obj.getValor())==null?1:(freqMap.get(obj.getValor())+1));
}
返回Collections.max(freqMap.values());
}
您的代码与您的描述不匹配。听起来你需要计算最常出现的valor
-是这样吗?是的,对不起,我很难用英语表达。是最常见的。例如,具有(0)(0)(0)(1)(1)的5个对象。你得到3。你的代码与你的描述不匹配。听起来你需要计算最常出现的valor
-是这样吗?是的,对不起,我很难用英语表达。是最常见的。例如,具有(0)(0)(0)(1)(1)的5个对象。你得到3。谢谢戴夫,我会试试的。谢谢戴夫,我会试试的。谢谢贝什。那看起来好多了。谢谢贝什。那样看起来好多了。