dcsimg
Collection - TreeSet
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Prasad_RS
Posted On:   Monday, February 26, 2007 04:26 AM

How to sort TreeSet values explicitly to desending order ascending order Sample Code: package Temp; import java.util.TreeSet; /** * @author prasad * */ public class sample { public static void main(String a[]){ TreeSet tr=new TreeSet(); tr.add("aa"); tr.add("bb"); tr.add("cc"); tr.add("dd"); System.out.println("tree set :" +tr); } } Out put : tree set :[aa, bb, cc, dd] I want to print in desending order    More>>

How to sort TreeSet values explicitly to desending order
ascending order

Sample Code:

package Temp;

import java.util.TreeSet;

/**
* @author prasad
*
*/
public class sample {

public static void main(String a[]){

TreeSet tr=new TreeSet();
tr.add("aa");
tr.add("bb");
tr.add("cc");
tr.add("dd");
System.out.println("tree set :" +tr);


}

}

Out put :


tree set :[aa, bb, cc, dd]


I want to print in desending order

   <<Less

Re: Collection - TreeSet

Posted By:   rahul123  
Posted On:   Wednesday, December 18, 2013 04:00 AM

by default TreeSet use comparable  interface compareTo() which is applicable for accending order.
if we want to sorting then  we should use comparator interface in this interface compare(Object obj1, Object obj2) method override . we can do sorting according to our requirement.

Ex,
TreeSet tr = new TreeSet(new Comparator()

public int compare( Object obj1,Object obj2 )
{
   return obj2.compareTo(obj1);
});

this is give the output in deccending order.

Re: Collection - TreeSet

Posted By:   Anonymous  
Posted On:   Monday, February 26, 2007 06:51 AM

Hi ,

TreeSet by default will sort in Ascending order if you want to sort it on any other order you can use the constructor of the TreeSet with the Comparator Object.


Comparator is an interface which will have compare and equals methods.you need to implement the compare method in the Comparator interface.The logic you need to write in the compare method is upto you in which way you wanted to sort the elements that you are going to insert in the TreeSet.for example see the code below


TreeSet tSet = new TreeSet( new Comparator() {

public int compare( Object o1,Object o2 ){


//your implementation of the comparemethod i.e either in //ascending or descending order
}

});

Regards,

Krishna Rajendra A.
About | Sitemap | Contact