狗有名字、体重和年龄3个属性:
public class Dog {
public String name; //名字
public double weight; //体重
public int age; //年龄
}
根据狗的年龄(age)排升序: Arrays.sort(dogs,(dog1,dog2)->dog1.age-dog2.age)
public static void main(String[] args) {
Dog[] dogs = new Dog[]{new Dog("嘟嘟",10.0,3),new Dog("毛毛",5.0,8),
new Dog("豆豆",12.0,2)};
Arrays.sort(dogs,(dog1,dog2)->dog1.age-dog2.age);
for (Dog dog : dogs) {
System.out.println(dog.toString());
}
}
根据狗的体重(weight)排降序: Arrays.sort(dogs,(dog1,dog2)-> (int) (dog2.weight-dog1.weight))
public static void main(String[] args) {
Dog[] dogs = new Dog[]{new Dog("嘟嘟",10.0,3),new Dog("毛毛",5.0,8),
new Dog("豆豆",12.0,2)};
Arrays.sort(dogs,(dog1,dog2)-> (int) (dog2.weight-dog1.weight));
for (Dog dog : dogs) {
System.out.println(dog.toString());
}
}