集合的排序

集合的排序

Set集合和List集合提供的子类都是线程不安全的。如果在多线程环境下必须要保证线程安全,可以使用集合的工具类来对集合进行操作。如Collections类,位于java.util包下,解释
this class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

方法sort():对集合里的元素进行排序操作(默认从小到大排序)
方法reverse():对集合里的元素进行反转操作
public void m15(){
        List<Integer> ls=new ArrayList<>();
        ls.add(-100);
        ls.add(13);
        ls.add(115);
        ls.add(128);
        System.out.println("------------排序前----------");
        ls.forEach(t -> System.out.print(t+" "));
        //对集合进行排序
        System.out.println();
        Collections.sort(ls);//sort 默认从小到大排序
        System.out.println("------------排序后----------");
        ls.forEach(t -> System.out.print(t+" "));
        //对集合元素进行反转
        Collections.reverse(ls);
        System.out.println();
        System.out.println("------------反转后----------");
        ls.forEach(t -> System.out.print(t+" "));
    }

除了默认的排序方法外,还可以实现集合的自定义排序:
自然排序:如果集合里的元素想自然排序,那么要求集合里的元素的应用类型必须实现Comparable接口,重写compareTo方法;
定制排序:不按照自然排序的方式排序,使用自定义的方式进行排序,可以实现Comparator接口,重写compare方法。

public void m16(){
        List<Student> students=new ArrayList<>();
        Student s1=new Student("Jack Sir","M",20);
        Student s2=new Student("Mack Miss","M",10);
        Student s3=new Student("Lisa Miss","M",18);
        Student s4=new Student("John","M",12);
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        System.out.println("-------排序前------");
        students.forEach(e -> System.out.println(e+" "));
        System.out.println("-----排序后---");
        Collections.sort(students,((o1, o2) -> {
        return o1.getsName().length()-o2.getsName().length();//字符串长度从小到大
    }));
        students.forEach(e -> System.out.println(e+" "));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值