1 PackageTest4;2 3 Importjava.util.ArrayList;4 Importjava.util.Collections;5 ImportJava.util.Comparator;6 ImportJava.util.HashMap;7 Importjava.util.List;8 ImportJava.util.Map;9 Ten Public classTest { One A Public Static voidMain (string[] args) { -map<string, integer> map =NewHashmap<string, integer>(); -Map.put ("D", 2); theMap.put ("C", 1); -Map.put ("B", 1); -Map.put ("A", 3); - +list<map.entry<string, integer>> infoids =
NewArraylist<map.entry<string, integer>>(Map.entryset ()); + //ArrayList (collection<? extends e> c) is an uncommon construction method of ArrayList,
Constructs a list of elements that contain the specified collection. A at //before sorting - for(inti = 0; I < infoids.size (); i++) { -String key=Infoids.get (i). GetKey (); - intValue=Infoids.get (i). GetValue (); -System.out.println (key+ ":" +value); - } in /*Output Result: - D:2 to b:1 + c:1 - A:3*/ the * //Sort $ //overriding the Compare methodPanax NotoginsengCollections.sort (Infoids,NewComparator<map.entry<string, integer>>() { - Public intCompare (map.entry<string, integer> O1, map.entry<string, integer>O2) { the //return (O2.getvalue ()-o1.getvalue ());//Sort by Value + return(O1.getkey ()). ToString (). CompareTo (O2.getkey ());//Sort by Key A } the }); + - //after sorting $ for(inti = 0; I < infoids.size (); i++) { $String key=Infoids.get (i). GetKey (); - intValue=Infoids.get (i). GetValue (); -System.out.println (key+ ":" +value); the } - //Sort by KeyWuyi //A:3 the //b:1 - //c:1 Wu //D:2 - //Sort by Value About //A:3 $ //D:2 - //b:1 - //c:1 - } A}
Two ways to sort HashMap