Common methods of "simple Java" HashMap

Source: Internet
Author: User
Tags concurrentmodificationexception

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.