如何使用Java中的比较器对字符串记录数组进行排序?

时间:2019-01-27 04:46:50

标签: java hashmap comparable

我有一个包含各个记录的字符串数组数据。即名字,姓氏,年龄,电子邮件地址,性别,地址。

示例:

static String[] users = {"Lola,Grimsdyke,89,lgrimsdyke0@facebook.com,Female,Newport Beach,CA","Sybilla,Martinetto,84,smartinetto1@google.it,Female,Anniston,AL","Casi,Roizn,78,croizn2@scribd.com,Female,San Jose,CA"};

如何使用可比较的界面提取每个用户记录并根据年龄对其进行排序?

1 个答案:

答案 0 :(得分:0)

首先,您必须将字符串数组转换为list。

 String[] users = { "Lola,Grimsdyke,89,lgrimsdyke0@facebook.com,Female,Newport Beach,CA",
                    "Sybilla,Martinetto,84,smartinetto1@google.it,Female,Anniston,AL",
                    "Casi,Roizn,78,croizn2@scribd.com,Female,San Jose,CA" };

            ArrayList<UserDetails> list=new ArrayList<>();
            for (int i = 0; i < users.length; i++) {
                String[] sp = users[i].split(",");
                list.add(new UserDetails(sp[0], sp[1], Integer.parseInt(sp[2]), sp[3], sp[4], sp[05]));
            }
            for(UserDetails detail:list) {
                System.out.println(detail);
            }

class UserDetails {
    String firstName;
    String lastName;
    int age;
    String emailId;
    String sex;
    String address;


    public UserDetails(String firstName, String lastName, int age, String emailId, String sex, String address) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.emailId = emailId;
        this.sex = sex;
        this.address = address;
    }


    @Override
    public String toString() {
        return "UserDetails [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", emailId="
                + emailId + ", sex=" + sex + ", address=" + address + "]";
    }


}

之后,创建agecomparator来比较年龄。

class AgeComparator implements Comparator<UserDetails> {
    @Override
    public int compare(UserDetails o1, UserDetails o2) {
         return o1.age - o2.age;
    }
}

使用比较器进行排序之后。

System.out.println("After Sort");
        AgeComparator ageComparator=new AgeComparator();
        Collections.sort(list, ageComparator);
        for(UserDetails detail:list) {
            System.out.println(detail);
        }