1: A simple example of using HashMap
Packagecom.pb.collection;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Set;ImportJava.util.Map.Entry; Public classHashmapdemo { Public Static voidMain (string[] args) {HashMap<string, string> HashMap =NewHashmap<string, string>(); Hashmap.put ("cn", "China"); Hashmap.put ("JP", "Japan"); Hashmap.put ("FR", "France"); System.out.println (HASHMAP); System.out.println ("CN:" + hashmap.get ("cn"))); System.out.println (Hashmap.containskey ("CN")); System.out.println (Hashmap.keyset ()); System.out.println (Hashmap.isempty ()); Hashmap.remove ("CN"); System.out.println (Hashmap.containskey ("CN")); //Traverse HashMap with iteratorIterator it =Hashmap.keyset (). iterator (); while(It.hasnext ()) {String key=(String) it.next (); System.out.println ("Key:" +key); System.out.println ("Value:" +Hashmap.get (key)); } //another way to traverse HashMapset<entry<string, string>> sets =Hashmap.entryset (); for(Entry<string, string>entry:sets) {System.out.print (Entry.getkey ()+ ", "); System.out.println (Entry.getvalue ()); } }}
2: An example of a combination of list and HASHMAP implementations
ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.HashMap;Importjava.util.ArrayList;ImportJava.util.Map;ImportJava.util.Scanner;ImportJava.util.Set;ImportJava.util.Map.Entry;/*** If you do not create a student class, enter n Student information (school number, name, age) from the keyboard, and then print out each student's information when the input is complete *@authorCcna_zhang **/ Public classAssignment { Public Static voidMain (string[] args) {//defines a list that holds student information, with an element type of HashMaplistNewArraylist(); Scanner input=NewScanner (system.in); System.out.println ("Please enter student's information, y means continue, n means exit"); while("Y". Equals (Input.next ())) {HashMap<string, object> map =NewHashmap<string, object>(); System.out.println ("Please enter the school number"); Map.put ("Studentno", Input.next ()); System.out.println ("Please enter your name"); Map.put ("Name", Input.next ()); System.out.println ("Please enter your age"); Map.put ("Age", Input.nextint ()); List.add (map); System.out.println ("Please continue to enter the student's information, y means continue, n means exit"); } System.out.println ("The Student information entered is:"); System.out.println ("Number of Students:" +list.size ()); IteratorList.iterator (); inti = 1; while(It.hasnext ()) {HashMap<string, object> stumap =It.next (); System.out.print ("First" + i + "Student's information"); System.out.println ("Study Number:" + stumap.get ("Studentno") + ", Name:" + stumap.get ("name") + ", Age:" + Stumap.get ("ages"))); } }}
Original: http://blog.csdn.net/woshisap/article/details/6887417
The use and traversal of HashMap in Java