- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
- public class TreeSetDemo {
-
- public static void main(String[] args) {
- TreeSet<String> ts=new TreeSet<String>(new StringLengthComparator());
- ts.add("aaabbbccc");
- ts.add("bbbaaaccc");
- ts.add("aabbc");
- ts.add("bddd");
-
- Iterator<String> it= ts.iterator();
-
- while(it.hasNext()){
- System.out.println(it.next());
- }
- }
- }
- //按字符串长度排序,如果相同则按字母排序
- class StringLengthComparator implements Comparator<String>{
- @Override
- public int compare(String o1, String o2) {
- if(o1.length()==o2.length()){
- return o1.compareTo(o2);
- }
- return o1.length()-o2.length();
- }
- }
复制代码
|
|