HashMap is very useful when a counter is required.
HashMap<String, Integer> countMap = new HashMap<String, Integer>(); //.... a lot of a's like the following if(countMap.keySet().contains(a)){ countMap.put(a, countMap.get(a)+1); }else{ countMap.put(a, 1); } |
1. Loop Through HashMap
Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); } |
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()); } |
2. Print HashMap
public static void printMap(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(); // avoids a ConcurrentModificationException } } |
3. Sort HashMap by Value
The following code example take advantage of a constructor of TreeMap here.
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; } // returning 0 would merge keys } } |
HashMap<String, Integer> countMap = new HashMap<String, Integer>(); //add a lot of entries 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); |
There are different ways of sorting HashMap, this way has been voted the most in stackoverflow.
very useful,thanks to god
The sort by value part is wrong 🙂
Look at this post : https://plus.google.com/+LouisWasserman/posts/bEQLDK712MJ
Louis Wasserman (yes, one of the Google Guava guys), actually dislikes this answer quite a bit: “It breaks in several really confusing ways if you even look at it funny. If the backing map changes, it will break. If multiple keys map to the same value, it will break. If you call get on a key that isn’t in the backing map, it will break. If you do anything whatsoever that would cause a lookup to happen on a key that isn’t in the map — a Map.equals call, containsKey, anything — it will break with really weird stack traces.”