当前位置:   article > 正文

java集合实现排序

java 实现集合排序
package com.bootdo.common.config.collection.vo;
/**
 * @ClassName :   Student
 * @Description: 第一种是实体类实现Comparable<Student> ,重写compareTo的方法
 * @Author: 13394
 * @CreateDate: 2018/10/18 12:41
 * @Version: 1.0
 */
public class Student implements Comparable<Student>{
    private String name;
    private Integer age;

    public Student(String name,Integer age) {
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        if(this.age>o.getAge()){
            return 1;
        }
        else if(this.age<o.getAge()){
            return -1;
        }
        else{
            return 0;
        }
    }
}
//测试的方法 
@Test
 public void test34(){
    List<Student> list=new ArrayList<Student>();
    Student s1=new Student("T-F", 18);
    Student s2=new Student("H胡歌", 28);
    Student s3=new Student("Z周润发", 50);
    Student s4=new Student("M梅兰芳", 100);
    list.add(s1);
    list.add(s4);
    list.add(s3);
    list.add(s2);
    System.out.println("------默认排序(按年纪)-------");
    Collections.sort(list);
    for (int i = 0; i < list.size(); i++) {
        Student student =  list.get(i);
        System.out.println(student.getAge()+","+student.getName());
    }

    Collections.sort(list,Collections.reverseOrder());
    for (int i = 0; i < list.size(); i++) {
        Student student =  list.get(i);
        System.out.println(student.getAge()+","+student.getName());
    }
}
//第二种的实现方法
@Test
public void test33() {
    List<Student> list = new ArrayList<Student>();
    Student s1 = new Student("T-F", 18);
    Student s2 = new Student("H胡歌", 28);
    Student s3 = new Student("Z周润发", 50);
    Student s4 = new Student("M梅兰芳", 100);
    list.add(s1);
    list.add(s4);
    list.add(s3);
    list.add(s2);
    Collections.sort(list, new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            if(o1.getAge()>o2.getAge()){
                return 1;
            }
            else if(o1.getAge()<o2.getAge()){
                return -1;
            }
            else{
                return 0;
            }
        }
    });
    for (int i = 0; i < list.size(); i++) {
        Student student =  list.get(i);
        System.out.println(student.getAge() + "," + student.getName());
    }
}

转载于:https://my.oschina.net/u/3653755/blog/2248705

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/440088
推荐阅读
相关标签
  

闽ICP备14008679号