A map is an object that maps a key to a value. A map cannot contain duplicate keys, and each key can be mapped to at most one value. When repeated additions occur, subsequent values will overwrite the previous one, which applies to the put () and Putall () two methods.
There are two common ways to traverse a map collection:
1, through key to find the corresponding value
2. Traverse the Map collection by a set set of key-value pairs
Public classPerson {//name PrivateString name; //Age Private intAge ; //non-parametric construction PublicPerson () {}//with a reference structure PublicPerson (String name,intAge ) { This. Age =Age ; This. Name =name; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override PublicString toString () {return"person{" + "name=" + name + ' \ ' + ", age=" + Age + '} '; }}
ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Set;/*** Map Collection Traversal*/ Public classMapdemo { Public Static voidMain (string[] args) {//Create a Map collection Objectmap<string, person> map =NewHashmap<string, person>(); //Create a Person object elementperson P1 =NewPerson ("Zhang Junbao", 30); Person P2=NewPerson ("Zhang San Feng", 80); Person P3=NewPerson ("Zhang", 110); //add an element to the map collectionMap.put ("001", p1); Map.put ("002", p2); Map.put ("003", p3); //traverse the Map collection//Method 1: Find value by Key//1.1 Get the set set of key correspondingSet<string> set =Map.keyset (); //1.2 Traversing the set of key for(String k:set) {//1.3 Gets the person object in the map collection based on keyPerson p =Map.get (k); System.out.println (k+ "* * *" + p.getname () + "* * *" +p.getage ()); } System.out.println ("----------------------------------------------"); //Method 2: Iterate through the set set of key-value pairs//2.1 Get key-value pairs set setset<map.entry<string, person>> entries =Map.entryset (); //2.2 Traversal key-value pairs set set for(Map.entry<string, person>p:entries) { //2.3 Get the corresponding key and valueString s =P.getkey (); Person Person=P.getvalue (); System.out.println (S+ "* * *" + person.getname () + "* * *" +person.getage ()); } }}
Traversal of the Map collection