HashMap, LinkHashMap, and TreeMap have their respective functions.
// TreeMap if you want to traverse the key in the natural or custom order, it is a good choice. It is the sorted key-value pair.
Map map = new TreeMap ();
Bytes -------------------------------------------------------------------------------------------------------
Import java. util. Comparator;
Import java. util. TreeMap;
Publicclass Demo {
Publicstaticvoid main (String [] args ){
// Natural state
TreeMap <String, String> treeMap1 = new TreeMap <String, String> ();
TreeMap1.put ("2", "1 ");
TreeMap1.put ("B", "1 ");
TreeMap1.put ("1", "1 ");
TreeMap1.put ("a", "1 ");
System. out. println ("result-treeMap1 =" + treeMap1 );
// Specify the sequencer
TreeMap <String, String> treeMap2 = new TreeMap <String, String> (new Comparator <String> (){
/*
* Int compare (Object o1, Object o2) returns an integer of the basic type,
* A negative number is returned, indicating that o1 is less than o2,
* If 0 is returned, the values of o1 and o2 are equal,
* A positive number indicates that o1 is greater than o2.
*/
Publicint compare (String o1, String o2 ){
// Specify the sorters in descending order
Return o2.compareTo (o1 );
}
});
TreeMap2.put ("2", "1 ");
TreeMap2.put ("B", "1 ");
TreeMap2.put ("1", "1 ");
TreeMap2.put ("a", "1 ");
System. out. println ("result-treeMap2 =" + treeMap2 );
}
}
Natural status: treeMap1 = {1 = 1, 2 = 1, a = 1, B = 1}
Descending status: treeMap2 = {B = 1, a = 1, 2 = 1, 1 = 1}
// Note: TreeMap refers to the case of an author on the Internet.
// LinkedHashMap is a sub-class of HashMap. If the output sequence is the same as that of the input, you can use LinkedHashMap to arrange it in the read order.
Map map = new LinkedHashMap ();
Map lhm = new LinkedHashMap ();
Lhm. put ("1", "sddddf ");
Lhm. put ("3", "2ddd22 ");
Lhm. put ("2", "3ddd33 ");
For (Iterator t = lhm. keySet (). iterator (); t. hasNext ();){
System. out. println (String) lhm. get (t. next ()));
}
Result:
Sddddf
2ddd22
3ddd33
// The key-value pairs stored in HashMap are random when they are retrieved. It stores data based on the key's HashCode value and can directly obtain its value based on the key, fast access speed. HashMap is the best choice for inserting, deleting, and locating elements in a Map.
Map map = new HashMap ();