File size: 2,409 Bytes
0284885 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | package Case1_package;
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
/*
定义数组并存储一些女朋友对象,利用Arrays中的sort方法进行排序
要求1:属性有姓名、年龄、身高。
要求2:按照年龄的大小进行排序,年龄一样,按照身高排序,身高一样按照姓名的字母进行排序
*/
//1、创建三个女朋友的对象
GirlFriend gf1 = new GirlFriend("xiaoshishi", 18, 1.67);
GirlFriend gf2 = new GirlFriend("xiaodandan", 19, 1.78);
GirlFriend gf3 = new GirlFriend("xiaohuihui", 19, 1.72);
//2、定义数组存储女朋友的信息
GirlFriend[] arr = {gf1, gf2, gf3};
//3、利用Arrays中的sort方法进行排序
//匿名内部类 Lambda表达式
Arrays.sort(arr, new Comparator<GirlFriend>() {
@Override
public int compare(GirlFriend o1, GirlFriend o2) {
//按照年龄的大小进行排序,年龄一样,按照身高排序,身高一样按照姓名的字母进行排序
double temp = o1.getAge() - o2.getAge();
temp = temp == 0 ? o1.getHeight() - o2.getHeight() : temp;
temp = temp == 0 ? o1.getName().compareTo(o2.getName()) : temp;
if (temp > 0) {
return 1;
} else if (temp < 0) {
return -1;
} else {
return 0;
}
}
});
//Lambda表达式
Arrays.sort(arr, (o1, o2) -> {
//按照年龄的大小进行排序,年龄一样,按照身高排序,身高一样按照姓名的字母进行排序
double temp = o1.getAge() - o2.getAge();
temp = temp == 0 ? o1.getHeight() - o2.getHeight() : temp;
temp = temp == 0 ? o1.getName().compareTo(o2.getName()) : temp;
if (temp > 0) {
return 1;
} else if (temp < 0) {
return -1;
} else {
return 0;
}
}
);
//4、展示一下数组中的内容
System.out.println(Arrays.toString(arr));
}
}
|