一般在map里取key的最大值是先排序,之后取出最大的一个即可。
import java.util.Arraysimport java.util.Collection
import java.util.HashMap
import java.util.Map
import java.util.Set
public class MaxMapDemo {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>()
map.put(1, 8)
map.put(3, 12)
map.put(5, 53)
map.put(123, 33)
map.put(42, 11)
map.put(44, 42)
map.put(15, 3)
System.out.println(getMaxKey(map))
System.out.println(getMaxValue(map))
}
/**
* 求Map<K,V>中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)
return obj[obj.size()-1]
}
/**
* 求Map<K,V>中Value(值)的最大值
* @param map
* @return
*/
public static Object getMaxValue(Map<Integer, Integer> map) {
if (map == null) return null
Collection<Integer> c = map.values()
Object[] obj = c.toArray()
Arrays.sort(obj)
return obj[obj.size()-1]
}
}
遍历容器,找到数值最大的int值,然后再次遍历,判断相等就返回所需的string.
下面是代码:
int nMax = 0
for(map<string,int>::iterator iter = clor.begin() iter != clor.end() ++iter)
{
int n = iter->second
if( n >nMax )
nMax = n
}
string stValue
for(map<string,int>::iterator iter = clor.begin() iter != clor.end() ++iter)
{
if(iter->second == nMax)
{
strValue = iter->first
break
}
}
容器map的遍历方法:
1、常规方法
2、利用keyset进行遍历,其优点在于可以根据所想要的key值得到想要的 values,更具灵活性。
3、比较复杂的一种遍历在这里,其灵活性极强,想得到什么就能得到什么。