java基础之Comparator和Comparable

有时我们需要对List或Map集合中的数据做顺序输出处理,可以用Comparator或Comparable
  • 用Comparator
//首先定义一个Bean对象
public class Student{
    private int id;
    private String name;
    ....setget、构造方法
}
//定义一个MyComparator类并实现Comparator接口
public class MyComparator implements Comparator<Student>{
    @Override
    public int compare(Student s1, Student s2) {
        return s1.getId()-s2.getId();
    }
}
//对于Set集合的实现类,在主方法中做比较输出
public static void main(String[] args) {
    Set<Student> set = new TreeSet<Student>(new MyComparator());
    set.add(new Student(1002, "张三"));
    set.add(new Student(1001, "李四"));
    set.add(new Student(1005, "王五"));
    set.add(new Student(1004, "唐人"));
    set.add(new Student(1008, "但丁"));
    set.add(new Student(1007, "林俊杰"));
    set.add(new Student(1009, "李逸"));

    for (Student student : set) {
        System.out.println(student);
    }
}
//对于List集合的实现类,在主方法中做比较输出
public static void main(String[] args) {
    List<Student> list = new ArrayList<Student>();
    list.add(new Student(1002, "张三"));
    list.add(new Student(1001, "李四"));
    list.add(new Student(1005, "熊志"));
    list.add(new Student(1004, "唐人"));
    list.add(new Student(1008, "但丁"));
    list.add(new Student(1007, "林俊杰"));
    list.add(new Student(1009, "李逸"));
    Collections.sort(list, new MyComparator());//第一个参数须是List集合的实现类
    Iterator<Student> it = list.iterator();
    while(it.hasNext()){
        System.out.println(it.next());
    }
}
  • 用Comparable
//定义Bean对象并实现Comparable接口
class Person implements Comparable<Object>{
    private int id;
    private String name;
    ....set、get、构造方法
    @Override
    public int compareTo(Object o) {
        Person p = (Person)o;
        return this.id-p.id;
    }
}
//比较输出
    public static void main(String[] args) {
        ArrayList<Person> arrayList = new ArrayList<Person>();
        // 不能写成:Collection c = new ArrayList();
        // 这会导致49行出错,因为Collections.sort()接受的形参必须的是List接口类型的变量,
        // Collections.sort()不能接受Collection类型的变量,这语法上编译时是通不过的
        arrayList.add(new Person(1000, "张思"));
        arrayList.add(new Person(1002, "李四"));
        arrayList.add(new Person(1001, "王五"));
        arrayList.add(new Person(1004, "小娟"));
        arrayList.add(new Person(1008, "老谢"));
        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println(arrayList.get(i));
        }
        java.util.Collections.sort(arrayList);//49行
        System.out.println("排序之后的内容是:");
        Iterator<Person> iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

但凡是对集合的操作, 我们应该保持一个原则就是能用 JDK 中的 API 就有 JDK 中的 API, 比如排序算法我们不应该 去 用 冒 泡 或 者 选 择 , 而 是 首 先 想 到 用 Collections 集 合 工 具 类,如下是一个面试题

  • 对HashMap排序,用Collections中的方法
public class HaspMapTest {
    public static void main(String[] args) {
        HashMap<Integer, Users> hashMap = new HashMap<Integer, Users>();
        hashMap.put(1, new Users(22, "小娟"));
        hashMap.put(3, new Users(21, "秀秀"));
        hashMap.put(2, new Users(28, "小列"));
        HashMap<Integer, Users> sortedHashMap = sortedHashMap(hashMap);
        System.out.println("排序后:");
        System.out.println(sortedHashMap);
    }
    private static HashMap<Integer, Users> sortedHashMap(HashMap<Integer, Users> hashMap) {
        // 首先拿到 map 的键值对集合
        Set<Entry<Integer,Users>> entrySet = hashMap.entrySet();
        // 将 set 集合转为 List 集合,为什么,为了使用工具类的排序方法
        ArrayList<Entry<Integer, Users>> list = new ArrayList<Entry<Integer,Users>>(entrySet);
        Collections.sort(list, new Comparator<Entry<Integer,Users>>() {
            @Override
            public int compare(Entry<Integer, Users> o1, Entry<Integer, Users> o2) {
                ///按照要求根据 User 的 age 的倒序进行排
                return o2.getValue().getAge()-o1.getValue().getAge();
            }
        });
        LinkedHashMap<Integer,Users> linkedHashMap = new LinkedHashMap<Integer, Users>();
        //将 List 中的数据存储在 LinkedHashMap 中
        for (Entry<Integer, Users> entry : list) {
            linkedHashMap.put(entry.getKey(), entry.getValue());
        }
        return linkedHashMap;
    }
}
ArrayList、HashSet、HashMap 都是线程不安全,如果想要线程安全,Collections 工具类提供了相关的 API,可以让上面那 3 个不安全的集合变为安全的
Collections.synchronizedCollection(c)
Collections.synchronizedList(list)
Collections.synchronizedMap(m)
Collections.synchronizedSet(s)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值