HashMap is useful when you need to count elements, as in the following example, counting the occurrences of each character in a string:
PackageSimplejava;ImportJava.util.HashMap;ImportJava.util.Map.Entry; Public classQ12 { Public Static voidMain (string[] args) {HashMap<integer, integer> countmap =NewHashmap<integer, integer>(); //.... A lot of a ' s like the followingString chars= "Abcabcabcghgk"; for(inti = 0; I < chars.length (); i++){ intA =Chars.charat (i); if(Countmap.keyset (). Contains (a)) {Countmap.put (a), Countmap.get (a)+ 1); } Else{countmap.put (A,1); } } for(Entry<integer, integer>E:countmap.entryset ()) {System.out.println (Char)(int) E.getkey () + "" +E.getvalue ()); } }}
Output Result:
G 2
B 3
C 3
A 3
K 1
H 1HASHMAP Traversal
Map<integer, integer> MP =NewHashmap<integer, integer>(); 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 =NewHashmap<integer, integer>(); for(Map.entry<integer, integer>Entry:map.entrySet ()) {System.out.println ("Key =" + entry.getkey () + ", Value =" +Entry.getvalue ()); }
Printing elements of HashMap
Public Static void Printmap (Map MP) { = mp.entryset (). iterator (); while (It.hasnext ()) { = (map.entry) It.next (); + "=" + Pairs.getvalue ()); // avoids a concurrentmodificationexception } }
Sort by value of key-value pairs
The following code passes a comparer to the TreeMap constructor to sort the map:
PackageSimplejava;ImportJava.util.Comparator;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.TreeMap;classValuecomparatorImplementsComparator<string>{Map<string, integer>Base; PublicValuecomparator (map<string, integer>base) { This. Base =Base; } Public intCompare (String A, string b) {if(Base.get (a) >=Base.get (b)) { return-1; } Else { return1; } //returning 0 would merge keys }} Public classQ12 { Public Static voidPrintmap (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 } } Public Static voidMain (string[] args) {HashMap<string, integer> countmap =NewHashmap<string, integer>(); //Add a lot of entriesCountmap.put ("A", 10); Countmap.put ("B", 20); Valuecomparator VC=NewValuecomparator (COUNTMAP); TreeMap<string, integer> sortedmap =NewTreemap<string, integer>(VC); Sortedmap.putall (COUNTMAP); Printmap (SORTEDMAP); }}
Although there are many ways to sort HashMap, the above approach is most respected in StackOverflow;
Note: Using a comparator comparator to sort the treemap, the comparator compares key by removing the value of the key corresponding to the size comparison;
Address: http://www.programcreek.com/2013/04/frequently-used-methods-of-java-hashmap/
Common methods of "simple Java" HashMap