1:39 am - Wednesday February 22, 2017

To create a Treeset with Comparator

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

This tutorial explains how  to implement your own sorting functionality with TreeSet.

To implement your own sorting functionality with TreeSet, you have to pass Comparator object     along with TreeSet constructor call.

The Comparator implementation holds the sorting logic. You have to override compare()     method to provide the sorting logic.

Example

import java.util.Comparator;

import java.util.TreeSet;

public class MySetWithCompr

{

    public static void main(String a[])

{         

       TreeSet<String> ts = new TreeSet<String>(new MyComp());

       ts.add("RED");

       ts.add("ORANGE");

       ts.add("BLUE");

       ts.add("GREEN");

       System.out.println(ts);

   }

}

class MyComp implements Comparator<String>

{

   @Override

   public int compare(String str1, String str2) {

       return str1.compareTo(str2);

   }
    

}

Output

          [BLUE, GREEN, ORANGE, RED]

BACK

Filed in: Java Examples

Comments are closed.