最简单的修改HashMap value值的方法

说到遍历,首先应该想到for循环,然而map集合的遍历通常情况下是要这样在的,先要获得一个迭代器。

Map<Integer,String> 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<Integer,Integer> m:map.entrySet())
				{
					if(arr[i]==(int)m.getKey())
						map.put((int)m.getKey(),(int)m.getValue()+1);
				}


附上一个完整的小程序例子。

随机生成长度为100的数组,数组元素为1到10,统计出现次数最多和最少的元素

import java.util.*;
class	Count 
{
	public void count(int[] arr)
	{
		int num=0;
		Map<Integer,Integer> map=new HashMap<Integer,Integer>();
		for(int i=1;i<=10;i++)
		{
			map.put(i,num);
		}
		for(int i=0;i<arr.length;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<Integer,Integer> m:map.entrySet())
				{
					if(arr[i]==(int)m.getKey())
						map.put((int)m.getKey(),(int)m.getValue()+1);
				}
		}
		for(Map.Entry<Integer,Integer> 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);
	}
}


供大家参考。

原文地址:https://www.cnblogs.com/jiangu66/p/3233631.html