将数据集合对某一字段进行排序

    List<Student> list = new ArrayList<>();
        list.add(new Student(1,25,"关羽"));
        list.add(new Student(2,25,"张飞"));
        list.add(new Student(3,18,"刘备"));
        list.add(new Student(4,32,"袁绍"));
        list.add(new Student(5,36,"赵云"));
        list.add(new Student(6,16,"曹操"));
        System.out.println("排序前:");
        for (Student student : list) {
            System.out.println(student.toString());
        }
        //使用默认排序
        List<Student> list2 = new ArrayList<>();
        list2.addAll(list);     //创建一个新的集合将list全部添加进来
        Collections.sort(list2,new Comparator<Student>() {     //将list2进行排序  从写方法    o2-o1返回的是从大到小
            @Override
            public int compare(Student o1, Student o2) {
                return o2.getAge()-o1.getAge();
            }
        });
        System.out.println("默认排序后:");
        for (Student student : list2) {
            System.out.println(student.toString());
        }
        Map<Integer, String> lmap = new LinkedHashMap<>();     //linkedHashMap将重复的key去掉
        for (Student tran : list2) {                      //将对比的年龄当做key存放在map中    这样子就会把相同的年龄都算作一个
            Integer key =tran.getAge();
            lmap.put(key, "0");
        }
        int m=0;
        for (Integer key : lmap.keySet()) {                           //循环key值   key值由大到小进行排序    排名也会被添加进value中
            lmap.put(key, (++m)+"");
        }
        for (Student tran : list) {
            for (Integer key : lmap.keySet()) {
                if(tran.getAge()==key) {                                 //循环list如何年龄一样的话  就将名次set进去
                    tran.setH(Integer.parseInt(lmap.get(key)));
                }
            }
        }
          System.out.println("按照年龄从大到小排序后:");
            for (Student student : list) {
                System.out.println(student.toString());
            }

//student类

  private int id;
        private int age;
        private String name;
        private int h;
        
        
        public int getH() {
            return h;
        }
        public void setH(int h) {
            this.h = h;
        }
        public Student(int id, int age, String name) {
            this.id = id;
            this.age = age;
            this.name = name;
        }
    
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return "Student [id=" + id + ", age=" + age + ", name=" + name + ", h=" + h + "]";
        }

猜你喜欢

转载自blog.csdn.net/weixin_42546892/article/details/88190597
今日推荐