2015-03-03 71 views
0

lst = [and, and, and, and, these, those, their, boxes, boxes]如何字符鍵轉換成字符串輸出一個HashMap

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]

+0

怎麼可能這種方法與'LST '返回'{a = 4,b = 2,t = 3}'?不是'{t = 2,q = 1,b = 2,f = 1,j = 1,o = 1,l = 1,d = 1}'? – Albert 2015-03-03 13:31:41

+0

對不起,使用了錯誤的列表示例。我剛編輯它 – FatFockFrank 2015-03-03 13:40:36

+0

「相關值」?你什麼意思? – laune 2015-03-03 13:43:50

回答

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; 
+0

感謝您的幫助。工作很好 – FatFockFrank 2015-03-03 15:23:23

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; 
+0

嗯,這似乎返回哈希表中的所有字符鍵.. [a,b,t] – FatFockFrank 2015-03-03 14:04:40

+0

我不這麼認爲。我實際上在本地測試它。 – Bram 2015-03-03 14:29:42

-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); } 
+0

'HashMap'中沒有'keys()'方法。它是'keyset()'。而你的代碼不會返回'[a]' – Albert 2015-03-03 14:02:15

+0

好眼睛,朋友。再說一遍,如果複製粘貼,我還是會提醒保留。 – Dragan 2015-03-03 14:18:34