【Java】对象数组按照某属性排序

有时候需要对对象列表或数组进行排序,下面提供两种简单方式:

方法一、将要排序的对象类实现< Comparable >接口。

要排序就要有比较的方法, 因为是自定义的类, 系统不知道怎么做两个自定义类的比较,

所以我们要自己在类内写两个类的比较的方法,也就是告诉按照那个属性或者那种方式来给对象数组排序

自定义比较算法也就是实现Comparable接口:(会自动生成需要自己写的方法如下图)

public class Good implements Comparable<Good>
{
    
    
	String name;
	int price;
	public Good(String name,int price) 
	{
    
    
		this.name=name;
		this.price=price;
	}
	@Override
	public int compareTo(Good good) {
    
    
		// TODO Auto-generated method stub
		return this.price-good.price;
	}
	
}

调用Collections.sort();

public static void main(String[] args) 
	{
    
    
		 ArrayList<Good> goods = new ArrayList<Good>();
		 goods.add(new Good("二", 2));
		 goods.add(new Good("三", 3));
		 goods.add(new Good("一", 1));
		 
		 System.out.println("排序前:");
	     for (Good good : goods)
	         System.out.println("姓名:"+good.name+" 价格:"+good.price);
	     
	     Collections.sort(goods);
	     
	     System.out.println("排序后:");
	     for (Good good : goods)
	         System.out.println("姓名:"+good.name+" 价格:"+good.price);
	}

方法二:使用Comparator匿名内部类实现。

class Student {
    
    

    String name;
    int age;
    int score;

    public Student(String name, int age,int score) {
    
    
        this.name = name;
        this.age = age;
        this.score = score;
    }
}
public class Test {
    
    

    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("大铭", 19, 89));
        students.add(new Student("来福", 26, 90));
        students.add(new Student("仓颉", 23, 70));
        students.add(new Student("王磊", 18, 80));

        System.out.println("排序前:");
        for (Student student : students) {
    
    
            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
        }

        Collections.sort(students,new Comparator<Student>() {
    
    

            @Override
            public int compare(Student o1, Student o2) {
    
    
                // TODO Auto-generated method stub
                return o1.age-o2.age;
            }
        });

        System.out.println("排序后:");
        for (Student student : students) {
    
    
            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
        }
    }
}

本文参考:
Java对对象按照其属性排序的两种方法

Java对象数组按照其属性排序的方法

猜你喜欢

转载自blog.csdn.net/qq_45654306/article/details/109085240