求一个Map中值最大的元素,最好列出键、值以及编号索引(即下标)

解决方案 »

  1.   

    看看这里吧:http://hi.baidu.com/zhouwei9960/blog/item/61f917009cb3af0e1c958343.html
      

  2.   

    遍历Map的values,同时遍历keySet,一个循环就找出了最大值和其对应的key;
    或者遍历Map 的entrySet也一样。
      

  3.   

    如果你想得到Map的键的最大值,可以覆盖将你的key对象去实现comparable接口,然后用
    keySet进行排序。或者直接使用Collections.sort(list,new Comparator<E>)进行排序。
    如果你想到Map的值的最大值,同上理,将value collection 进行排序
      

  4.   

    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    public class Test {
    public static void main(String args[]){
    Map<String,Integer> map = new HashMap<String,Integer>();
    int maxValue = 0;
    String maxKey = null;
    map.put("sg", 17);
    map.put("gewg", 263);
    map.put("ge", 4);
    map.put("gwe", 34);
    Iterator it = map.entrySet().iterator();
    for(int i=0;i<map.size();i++){
    Map.Entry entry =(Map.Entry)it.next();
    int value = Integer.parseInt(entry.getValue().toString());
    if(value > maxValue){
    maxValue = value;
    maxKey = entry.getKey().toString();
    }
    }
    System.out.println("maxValue="+maxValue+",its key is "+maxKey);
    }
    }
      

  5.   

    TreeMap中lastKey可以返回最大的键值
      

  6.   

    5楼的,如果Map 中的值有重复怎么办
      

  7.   


    public static void main(String[] args) {
    int[] data = { 3, 3, 5, 1, 3, 5, 3, 5, 5, 8 };
    Map<Integer, Integer> m = new HashMap<Integer, Integer>();
    for (int i = 0; i < data.length; i++) {
    if (m.get(data[i]) == null) {
    m.put(data[i], 1);
    } else {
    m.put(data[i], m.get(data[i]) + 1);
    }
    }
    System.out.println("Map里的元素: " + m); int t = 0;
    Set<Map.Entry<Integer, Integer>> set = m.entrySet();
    for (Entry<Integer, Integer> entry : set) {
    if (entry.getValue() > t) {
    t = entry.getValue();
    }
    } System.out.println("次数最多的有:");
    for (Entry<Integer, Integer> entry : set) {
    if (entry.getValue() == t) {
    System.out.println(entry.getKey());
    }
    }
    }
    }