Java TreeSet with Comparator sorting

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.