import java.util.HashMap;Output:
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Triclés {
public static void main(String[] args) {
Map< String,String> hmap = new HashMap< String,String> ();
hmap.put("4", "four");
hmap.put("2", "two");
hmap.put("3", "three");
hmap.put("1", "one");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
System.out.println("Before sorting:");
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map sortedMap = new TreeMap(hmap);
Set set2 = sortedMap.entrySet();
Iterator iterator2 = set2.iterator();
System.out.println("After sorting:");
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
}
Before sorting:
3: three
2: two
1: one
4: four
After sorting:
1: one
2: two
3: three
4: four
import java.util.Collections;Output:
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Triclés {
public static HashMap< String, String> sortHashMap(Map< String, String> hmap){
List< Map.Entry< String, String> > list =
new LinkedList< Map.Entry< String, String> > ( hmap.entrySet() );
Collections.sort( list, new Comparator< Map.Entry< String, String> > (){
public int compare
(Map.Entry< String, String> o1, Map.Entry< String, String> o2 )
{
//compare two keys
return (o1.getKey()).compareTo( o2.getKey() );
}
});
//create a new HashMap from LinkedList
HashMap< String, String> hmapTriee = new LinkedHashMap< String, String> ();
for (Map.Entry< String, String> entry : list)
{
hmapTriee.put( entry.getKey(), entry.getValue() );
}
return hmapTriee;
}
public static void main(String[] args) {
final HashMap< String, String> hmap = new HashMap< String, String> ();
hmap.put("4", "four");
hmap.put("2", "two");
hmap.put("3", "three");
hmap.put("1", "one");
System.out.println("Before sorting: "+ hmap);
System.out.println("After sorting: "+sortHashMap(hmap));
}
}
Before sorting: {3=three, 2=two, 1=one, 4=four}
After sorting: {1=one, 2=two, 3=three, 4=four}
Please disable your ad blocker and refresh the window to use this website.