说到遍历,首先应该想到for循环,然而map集合的遍历通常情况下是要这样在的,先要获得一个迭代器。
Map map = new HashMap<>();
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
实际上一个foreach循环也是可以的,很简洁吧~
for(Map.Entry m:map.entrySet())
{
if(arr[i]==(int)m.getKey())
map.put((int)m.getKey(),(int)m.getValue()+1);
}
附上一个完整的小程序例子。
import java.util.*;
classCount
{
public void count(int[] arr)
{
int num=0;
Map map=new HashMap();
for(int i=1;i<=10;i++)
{
map.put(i,num);
}
for(int i=0;i
{
/*Iterator it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry m=(Map.Entry)it.next();
if(arr[i]==(int)m.getKey())
map.put((int)m.getKey(),(int)m.getValue()+1);
}*/
for(Map.Entry m:map.entrySet())
{
if(arr[i]==(int)m.getKey())
map.put((int)m.getKey(),(int)m.getValue()+1);
}
}
for(Map.Entry m:map.entrySet())
{
System.out.println(""+m.getKey()+"出现的次数为:"+m.getValue()+"次");
}
}
public static void main(String[] args)
{
Random rd=new Random();
int[] arr=new int[100];
for(int i=0;i<100;i++)
{
arr[i]=rd.nextInt(10)+1;
}
new Count().count(arr);
}
}
供大家参考。