Monday 24 February 2014

Short and Effective way to Sort a Set with its Key in Java

Many times we need to sort the data to represent in a particular order.
Here is a trick  to sort the data sets in Java. In this example i am using an unordered MapSet to demonstrate the sorting of MapSet with its key.


Map<String,String> maps_set=new Map<String,String>;

maps_set.put("Java","developed by SunMicroSystems");

 maps_set.put("CSHARP","developed by Microsoft");

 maps_set.put("PYTHON","Python Organization");



 SortedSet<string> keys=new TreeSet(maps_set.keySet());//Here the Keys were sorted by the TreeSet and placed in the keys object

  System.Out.Println("Key         Value");

 foreach (String key : keys) {
      System.Out.Println("Maps_Key:"+key+"  Map_Value:"+maps_set.get(key));
}


In the above example the I had put the 3 values into the maps_set and they are not in a alphabetical order 

No comments: