Import java.util.*;/* Exercise: Sort by string length. The string itself is comparable, but the way it is compared is not required. At this point, you can only use the comparator note: in mode two: int num=new integer (str1.length ()). CompareTo (New Integer (Str2.length ())); There are three possible values for NUM at this time. Positive, negative, zero. Never write the following code: if (num==1) return 1;num does not necessarily equal 1. The 0,1,-1 we return in the function represents only three cases: 0, positive, negative. This must be noted. */class Mycompare implements Comparator//Custom Comparator {public int compare (Object obj1,object obj2) {if (! ( Obj1 instanceof String) | | ! (Obj2 instanceof String)) throw new RuntimeException ("Not a string! "); String str1= (String) obj1; String str2= (String) obj2;/* way One if (Str1.length () >str2.length ()) Return 1;if (Str1.length () ==str2.length ()) {return Str1.compareto (STR2);} return-1;*//* mode two */int num=new integer (Str1.length ()). CompareTo (New Integer (Str2.length ())); if (num==0) {return Str1.compareto (STR2);} return num;}} If there is no custom class above, then the TreeSet will be sorted in natural order (the letter of the string is naturally sorted) class TreeSetTest1 {public static void main (string[] args) {TreeSet ts= New TreeSet (New Mycompare ()),//treeset ts=new TreeSet (), Ts.add ("ABCD"), Ts.add ("DGF"); Ts.add ("Aakuop"); Ts.add ("Po") ; ts.add("Hello"), Ts.add ("Hello"), Ts.add ("World"), Ts.add ("Werttif"); Ts.add ("Hello"); Iterator It=ts.iterator (); while ( It.hasnext ()) {SOP ((String) It.next ());}} public static void Sop (Object obj) {System.out.println (obj);}}
Java Collection Framework-treeset exercises