java List根据元素进行升序降序排序

首先实体类需要实现 Comparable 接口

实现compareTo()方法

下面是降序 如果需要升序则把位置交换一下就好了

然后调用Collections.sort(list);

 public static void main(String[] args) {
        List list=new ArrayList();

        list.add(new Student("张三","WN001",88));
        list.add(new Student("李四","WN002",75));
        list.add(new Student("王五","WN003",99));
        list.add(new Student("赵六","WN004",58));
        list.add(new Student("田七","WN005",67));
        list.add(new Student("小八","WN006",58));
        list.add(new Student("唐七","WN007",35));
        list.add(new Student("商十","WN008",78));

        Collections.sort(list);
        for (int i = 0; i 

java List根据元素进行升序降序排序_第1张图片

public class Student implements Comparable{
    private String name;
    private String id;
    private int score;


//............省略构造函数和GET SET 方法
 

    @Override
    public int compareTo(Student o) {
        return o.getScore()-this.score  ;
    }
}

 

你可能感兴趣的:(数组遍历方式)