这是自己的关于map集合的相关操作的小研究,分享给大家。

主要代码内容包含以下:

1,map集合的遍历

2,根据key值获取value值

3,根据value值获取key值

4,返回最大value值对应的key值

5,获取最大key值,最小key值,最大value值,最小value值

上代码:

  1   @Test
public void bb1(){//测试代码
Integer value=0;
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
map.put(1, 12);
map.put(2, 13);
map.put(4, 11);
map.put(7, 22);
map.put(3, 55); //map集合的遍历
Iterator<Integer> i = map.keySet().iterator(); while(i.hasNext()){
Integer next = i.next();
System.out.println("key2值:"+next+"----"+"value值:"+map.get(next));//key值是自然排序的
}
System.out.println("最大值Key值"+getMaxKey(map));
System.out.println("最小值Key值"+getMinKey(map));
System.out.println("最大值val值"+getMaxVal(map));
System.out.println("根据value值获取key值:"+getKeyByVal(map,55));
System.out.println("返回最大值value对应的key值:"+getKeyByMaxValue(map,value));
System.out.println("根据key值获取对应的value值:"+getValByKey(map,1)); } /**
* 根据key值获取value值
* @param map
* @param key
* @return
*/
public static Object getValByKey(Map<Integer,Integer> map,Integer key){
Integer value=0;
for(Integer getVal:map.values()){
if(getVal==map.get(key)){
value=getVal;
}
}
return value;
}
/**
* 求最大key值
* @param map
* @return
*/
public static Object getMaxKey(Map<Integer,Integer> map){
if(map==null){
return null;
}
Set<Integer> set=map.keySet();
Object[] obj = set.toArray();
Arrays.sort(obj);//sort升序排序
return map.get(obj[obj.length-1]);//获得最大key值对应的value值
// return obj[obj.length-1];
}
/**
* 获取最大value值
* @return
*/
public static Object getMaxVal(Map<Integer,Integer> map){
if(map==null){
return null;
}
Collection<Integer> val = map.values();
Object[] obj = val.toArray();
Arrays.sort(obj);
// return obj[0];//获取最小value
return obj[obj.length-1];//获取最大value
}
/**
* 返回最小的key值
* @param map
* @return
*/
public static Object getMinKey(Map<Integer,Integer> map){
if(map==null){
return null;
}
Set<Integer> set = map.keySet();
Object[] obj = set.toArray();
Arrays.sort(obj);
return obj[0]; }
/**
* 根据value值获取对应的key值
* @return
*/
public static String getKeyByVal(Map<Integer,Integer> map,Integer value){
Integer key=0;
for(Integer getKey:map.keySet()){
if(map.get(getKey)==value){
key=getKey;//这个key值最后一个满足条件的key值
} }
return "value值为:"+value+"对应的key值为:"+key;
}
/**
* 返回最大值对应的key值
* @param map
* @param value
* @return
*/
public static Integer getKeyByMaxValue(Map<Integer,Integer> map,Integer value){
Integer maxVal =(Integer) getMaxVal(map);
value=maxVal;
Integer key=0;
for(Integer getKey:map.keySet()){
if(map.get(getKey)==value){
key=getKey;
}
}
return key;
}

欢迎批评,交流和指正,谢谢!

05-06 02:47