如何将字符键转换为hashmap的String输出

时间:2015-03-03 13:23:15

标签: java hashmap

lst = [and, and, and, and, these, those, their, boxes, boxes]

 public Collection<Character> mostCommonFirstWeighted() {
        HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();
            for (String s : lst) {
            if (hashmap.get(s.charAt(0)) == null) {
                hashmap.put(s.charAt(0), 1);
            } else {
                hashmap.put(s.charAt(0), hashmap.get(s.charAt(0)).intValue() + 1);
            }
        }
        System.out.println(hashmap);

hashmap = {a=4, b=2, t=3}

现在我如何让我的hashmap返回仅具有最高相关值的密钥。

期望的输出:

[a]

3 个答案:

答案 0 :(得分:1)

一种方法可能是:

Collection<Integer> values = hashmap.values(); // get values
List<Integer> listVal = new ArrayList<Integer>(values); 
Collections.sort(listVal, new Comparator<Integer>() { // sort in decreasing order 
    public int compare(Integer o1, Integer o2) {
        return - o1.compareTo(o2); 
    }
});

Integer maxVal = listVal.get(0); // get first (max value)

Collection<Character> returns = new ArrayList<Character>(); 

for (Map.Entry<Character, Integer> entry : hashmap.entrySet()) {
    if (entry.getValue().intValue() == maxVal.intValue()) { 
        returns.add(entry.getKey());  // get all keys that matches maxVal
    }
}

return returns; 

答案 1 :(得分:0)

您的意思是指具有最多值的条目吗?

int max = 0;
    Collection<Character> c = new ArrayList<>();
    for (Map.Entry<Character, Integer> e: hashmap.entrySet()) {
        int v = e.getValue();
        if (v >= max) {
            if (v > max) {
                c.clear();
                max = v;
            }
            c.add(e.getKey());
        }
    }
    System.out.println(c);  
    return c;

答案 2 :(得分:-1)

我猜你想用同样的方法打印这些值,所以你可以试试这个。我没有对它进行测试,也没有将它与编译器进行比较,可能需要在这里和那里进行一些调整......

if ( !hashmap.isEmpty() ) {
     Set<Character> chars = hashmap.keys();
     Iterator<Character> rator = chars.interator();
     Integer max = hashmap.get( (Character)chars.toArray()[0] );
     Integer tmp;
     while( rator.hasNext() ) {
           tmp = hashmap.get( (Character)rator.next() );
           if ( tmp >= max ) 
                 rator.remove()
     }
     System.out.println(chars); }