示例:
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"};
如何使用可比较的界面提取每个用户记录并根据年龄对其进行排序?
答案 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);
}