Java实现根据属性排序输出对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现根据属性排序输出对象相关的知识,希望对你有一定的参考价值。

package com.wms;

import java.util.Arrays;

public class DogAgeSort {

    public static void main(String[] args) {

        Dog[] dogs = {new Dog("小黄",2), new Dog("小绿",1), new Dog("小黑",3) , new Dog("小红",6)};
        Arrays.sort(dogs, new DogComparator());
        
        for(Dog dog: dogs){
            System.out.println(dog);
        }
        
    }

}
package com.wms;

public class Dog {

    private String name;
    private int age;
    
    
    public Dog() {}
    public Dog(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Dog [name=" + name + ", age=" + age + "]";
    }
    
}
package com.wms;

import java.util.Comparator;

public class DogComparator implements Comparator<Dog>{

    public int compare(Dog o1, Dog o2) {
        if(o1.getAge()<o2.getAge()){
            return -1;
        }else if(o1.getAge()>o2.getAge()){
            return 1;
        }else{
            return 0;
        }
    }




}

 

以上是关于Java实现根据属性排序输出对象的主要内容,如果未能解决你的问题,请参考以下文章

JAVA实现根据对象的属性排序--BeanComparator,FixedOrderComparator,ComparatorChain

Python入门题045:根据对象属性进行排序

java 循环把对象属性 输出

java 集合存储对象且根据对象属性排序

C# list<>根据对象的某个属性排序

java 如何对对象进行排序