HashMap and HashSet are two important members of the Java Collection Framework, where HashMap is the common implementation class of the Map interface
1: Create a class first
1 package day; 2 Import java.util.ArrayList; import Java.util.HashMap; import java.util.Iterator; import Java.util.Map; import java.util.Map.Entry; import Java.util.Set; 4 Import Javax.swing.JComboBox.KeySelectionManager; 6 Public class Text {
When created, the second step begins.
2: Use HashMap to store information from multiple countries of course it has to be written in the Main method
Public Static void Main (string[] args) { 1 map<string,string>map=new hashmap<string,string> ();
3: Add the country we want to add in HashMap
To establish a key-value mapping between a national abbreviation and a Chinese name, such as CN counterpart → China, can be found in China according to "cn", delete can be deleted, let us do the next step
1 map.put ("CN", "China"); 2 Map.put ("USA", "USA"); 3 Map.put ("UD", "United Nations");
Add the element with the put method above, consistent with the Add method of the other collection (linkedlist,arraylist), but there is no Add method in the method of map here.
4: The first solution to add, this method is also difficult
System.out.print (Map.size ()); for (entry<string, string> item:map.entrySet ()) { System.out.println (String.Format ("key is%s\ Nvalues is%s ", Item.getkey (), Item.getvalue ())); }
The second scenario:
set<string>keyset=Map.keyset (); for (String key:keyset) { System.out.println ("key is" +key+ "\nvalue is" +Map.get (key)); }
The third scenario:
set<string>set=Map.keyset (); Iterator<string>iterator=set.iterator (); while (Iterator.hasnext ()) { String key=iterator.next (); System.err.println ("key is" +key+ "value is" +Map.get (key)); }
Three super-hard-to-remember conveniences for HashMap collections in Java