package com.monkey1024.set; import java.util.Comparator; import com.monkey1024.bean.Person; public class CompareByNameLength implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { //根据name长度进行排序 int num = p1.getName().length() - p2.getName().length(); if(num == 0){ num = p1.getName().compareTo(p2.getName()); if(num == 0){ num = p1.getAge() - p2.getAge(); } } return num; } }
测试类,向TreeSet的构造方法中传入CompareByNameLength对象
package com.monkey1024.set; import java.util.TreeSet; import com.monkey1024.bean.Person; /** * TreeSet可以对元素进行排序 * 使用TreeSet根据name长度进行排序 * */ public class TreeSetTest03 { public static void main(String[] args) { TreeSet<Person> ts = new TreeSet<>(new CompareByNameLength()); ts.add(new Person("tony", 23)); ts.add(new Person("jordan", 20)); ts.add(new Person("tim", 22)); ts.add(new Person("james", 24)); ts.add(new Person("an", 21)); System.out.println(ts); } }
练习:
1.将一个字符串中的字符按照字典顺序进行排序,要保留重复的字符。例如输入:java,打印aajv
答案:
1.向输入的字符串转换为字符数组,然后向TreeSet中添加字符
package com.monkey1024.set.exercise; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; /** * 问题:将一个字符串中的字符按照字典顺序进行排序,要保留重复的字符。例如输入:java,打印aajv * 分析:向输入的字符串转换为字符数组,然后向TreeSet中添加字符 */ public class Exercise03 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //创建键盘录入对象 System.out.println("请输入一行字符串:"); String line = sc.nextLine(); //将键盘录入的字符串存储在line中 char[] arr = line.toCharArray(); //将字符串转换成字符数组 TreeSet<Character> ts = new TreeSet<>(new Comparator<Character>() { @Override public int compare(Character c1, Character c2) { int num = c1.compareTo(c2); //保存重复数据 return num == 0 ? 1 : num; } }); for(char c : arr) { ts.add(c); } for(Character ch : ts) { System.out.print(ch); } } }