java - Sort HashMap keys and store in ArrayList -
i need task of sorting hashmap
keys string , store them in arraylist
. have written below piece of code
public static list<string> getsortedlistbykeys(hashmap<string,string> keysdictionary) { list<string> sortedkeyslist = null; sortedset<string> sortedkeysset = null; if(keysdictionary == null || keysdictionary.size() == 0){ return null; } sortedkeysset = new treeset<>(keysdictionary.keyset()); sortedkeyslist = new arraylist<>(sortedkeysset); return sortedkeyslist; }
i have run , working fine.
just want know if there better way achieve same
since want sort strings based on natural ordering itself, directly create list , use collections.sort()
on it.
sortedkeyslist = new arraylist<>(keysdictionary.keyset()); collections.sort(sortedkeyslist);
this way can avoid using sortedset
intermediate step.
Comments
Post a Comment