
闲来无事做翻译:原文地址
1、用来做统计
1 2 3 4 5 6 7 8
|
HashMap<String, Integer> countMap = new HashMap<String, Integer>(); if(countMap.keySet().contains(a)){ countMap.put(a, countMap.get(a)+1); }else{ countMap.put(a, 1); }
|
2、遍历HashMap
1 2 3 4 5
|
Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); }
|
1 2 3 4
|
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
|
3、打印HashMap
1 2 3 4 5 6 7 8
|
public static void (Map mp) { Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); it.remove(); } }
|
4、按照value值对hashmap排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class ValueComparator implements Comparator<String> { Map<String, Integer> base; public ValueComparator(Map<String, Integer> base) { this.base = base; } public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } } }
|
1 2 3 4 5 6 7 8 9 10 11
|
HashMap<String, Integer> countMap = new HashMap<String, Integer>(); countMap.put("a", 10); countMap.put("b", 20); ValueComparator vc = new ValueComparator(countMap); TreeMap<String,Integer> sortedMap = new TreeMap<String,Integer>(vc); sortedMap.putAll(countMap); printMap(sortedMap);
|
这个是被Stack Overflow点赞最多的一种排序方法
近期评论