TreeSet guarantees no duplicate data, also guarantees long (n) Time complexity for Add (), remove (), contains ().
ImportJava.util.Comparator;ImportJava.util.TreeSet; Public classMYSETWITHCOMPR { Public Static voidMain (String b[]) {TreeSet<MyComp> ts =NewTreeset<mycomp> (NewMYCOMPC ()); Ts.add (NewMyComp ("RED", 1)); System.out.println ("Added"); Ts.add (NewMyComp ("ORANGE", 1)); System.out.println ("Added"); Ts.add (NewMyComp ("BLUE", 1)); System.out.println ("Added"); Ts.add (NewMyComp ("GREEN", 1)); System.out.println ("Added"); Ts.add (NewMyComp ("GREEN", 2)); System.out.println ("Green 2 Added"); for(MyComp a:ts) {System.out.println (A.name+ " " +A.I); } }} classMyCompImplementsComparable<mycomp> { PublicString name; Public inti; PublicMyComp (String N,intX) {name = n; i =x;} @Override Public intCompareTo (MyComp entry) {if(Name.equals (entry.name)) {System.out.println ("Local name =" +name); System.out.println ("Local i =" +i); System.out.println ("Entry name =" +entry.name); System.out.println ("Entry I =" +entry.i); Entry.i= i;//Update this as the duplicate data gets inSystem.out.println ("Local name =" +name); System.out.println ("Local i =" +i); System.out.println ("Entry name =" +entry.name); System.out.println ("Entry I =" +entry.i); return0; } Else { returnName.equals (entry.name)? -1:1; } }}classMycompcImplementsComparator<mycomp>{@Override Public intCompare (MyComp str1, MyComp str2) {returnStr1.compareto (STR2); } }
Entry name = GREEN
Entry I = 2
Green 2 Added
RED 1
ORANGE 1
BLUE 1
GREEN 2 (see, this value is updated)
Java TreeSet with Comparator sorting