2012-01-20 131 views
0

如何在每次运行此循环时使用我目前设置的所有元素只映射到映射的方式在此情况下将键[i]增加1为1.我试图找出每个数字出现多少次。我在list.get(i)之后的空点上尝试了+1,但是只是将每个元素映射为1.谢谢。尝试使用Hashmap <Integer,Integer>

List<Integer> list = new ArrayList<Integer>(); 
    HashMap<Integer,Integer> Mode = new HashMap<Integer, Integer>(); 
    for (int i = 0; i < arr.length; i++) { 
     for (int j = 0; j < arr[i].length; j++) { 
      list.add(arr[i][j]); 
     } 
    } 
    System.out.println(list); 
    int count = 1; 
    for(int i = 0; i < list.size(); i ++) { 
     Mode.put(list.get(i),); 
+0

int count = 1可以忽略! – Kristopher

+0

你的问题不是很理解,但评论是好的 – Kushan

+0

哈哈对不起,从10AM MT时间开始就对这些作业感到抱歉,谢谢你的帮助,我真的很感激它 – Kristopher

回答

1

如果可以选择,你会发现它更容易使用类似MultisetGuava

Multiset<Integer> seen = HashMultiset.create(); 
for (int[] row : arr) { 
    for (int elem : row) { 
    seen.add(elem); // none of that nasty dealing with the Map 
    } 
} 
// you can look up the count of an element with seen.count(elem) 
E mostCommon = null; 
int highestCount = 0; 
for (Multiset.Entry<Integer> entry : seen.entrySet()) { 
    if (entry.getCount() > highestCount) { 
    mostCommon = entry.getElement(); 
    highestCount = entry.getCount(); 
    } 
} 
return mostCommon; // this is the most common element 
+0

如果您不能使用第三方库 - 可能是这种情况,如果这是家庭作业 - 您应该使用AVD的解决方案。 –

3

您需要在此处指定Key

for(int i = 0; i < list.size(); i++) { 
     int value=list.get(i); 
     if(!Mode.containsKey(value)) 
      Mode.put(value,1); 
     else 
      Mode.put(value,Mode.get(value)+1); 
} 
+0

@AVD是对的。或者你的问题不清楚。根据我的理解,您正在计算数组中出现值的次数。因此,您使用该值作为您的地图的关键字,然后将出现次数作为地图值。这正是建议的内容。如果这不正确,请澄清您的问题并解释为何所提供的解决方案无效。 –

+0

已编辑的解决方案的第一篇文章没有工作 – Kristopher

2

根据您的意见,

for(int i = 0; i < list.size(); i ++) { 
    if(Mode.containsKey(list.get(i))){ 
     Integer count = Mode.get(list.get(i)); 

     Mode.put(list.get(i), ++count);} 
    else 
     Mode.put(list.get(i), 1); 
相关问题