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 68 69 70 71 72 73 74 75 76 77 78 79
| package com.hao;
import java.util.ArrayList; import java.util.Comparator; import java.util.List;
public class Main { public static void main(String[] args) {
List<User> list = new ArrayList<>(); list.add(new User("lilei", "male", 11, 120)); list.add(new User("hanmeimei", "female", 10, 126)); list.add(new User("zhaolaoshi", "male", 54, 100)); list.add(new User("lilaoshi", "female", 41, 150)); list.add(new User("xiaozhang", "female", 75, 155)); list.add(new User("laozhuren", "male", 55, 145)); list.add(new User("shenayi", "female", 19, 127)); list.sort(comparator); for (User user : list) { System.out.println(user); } }
public static Comparator<User> comparator = new Comparator<User>() { @Override public int compare(User o1, User o2) { int result = 0; if (o1.age <= 12 && o2.age > 12) { result = -1; } else if (o2.age <= 12 && o1.age > 12) { result = 1; } else { if (o1.sex.equals("female") && !o2.sex.equals("female")) { result = -1; } else if (o2.sex.equals("female") && !o1.sex.equals("female")) { result = 1; } else { int a = o1.point - o2.point; if (a != 0) { result = a > 0 ? -1 : 1; } else { result = 0; } } } return result; } }; }
class User { String name; String sex; int age; int point;
public User(String name, String sex, int age, int point) { this.name = name; this.sex = sex; this.age = age; this.point = point; }
@Override public String toString() { return "User{" + "name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + ", point=" + point + '}'; } }
JAVA
|