Map has its own sort function, but it needs to rewrite the sorting method, the code is as Follows:
packagecoreJava.com.shindo.corejava.map;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.Comparator;Importjava.util.HashMap;Importjava.util.List;Importjava.util.Map;Importjava.util.Map.Entry; public classMapsort {/*** * @Title: sortmap * @Description: sort the data in the collection alphabetically by key*/ publiclist<map.entry<string, string>> Sortmap (Finalmap<string, string>Map) { Finallist<map.entry<string, string>> infos =Newarraylist<map.entry<string, string>>(map.entryset ()); //to override the sorting method for a collection: in alphabetical orderCollections.sort (infos,Newcomparator<map.entry<string, string>>() {@Override public intCompareFinalentry<string, string> o1,Finalentry<string, string>O2) { return(o1.getkey (). toString (). compareTo (o2.getkey ())); } }); returninfos; } public Static voidMainFinalstring[] Args) { Finalmap<string, string> map =Newhashmap<string, string>(); Map.put ("charSet", "utf-8"); Map.put ("merid", "5412"); Map.put ("acqid", "321"); Finallist<map.entry<string, string>> list =Newmapsort (). Sortmap (map); for(Finalmap.entry<string, string>M:list) {System.out.println (m.getkey ()+ ":" +M.getvalue ()); } }}
Execute the main method with the following results:
acqid:321charset:utf-8merid:5412
The contents of the map are sorted in alphabetical order