List对象中存放多个Person对象(此对象包含,名字,年龄、id)。按Person的年龄从小到大排序,假设年龄相等的话再按名字的大小来排序。求出年龄最大的那个学生信息。
第一种,搞麻烦了
person
package Test3_30.t3;
public class Person {
private String name;
private String id;
private int age;
public Person() {
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", age=" + age +
'}';
}
public Person(String name, String id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
test
package Test3_30.t3;
import java.util.*;
public class test3 {
public static void main(String[] args) {
List<Person> list=new ArrayList<>();
list.add(new Person("tom","9527",25));
list.add(new Person("jim","9528",29));
list.add(new Person("danny","9529",14));
list.add(new Person("ZhangSan","9530",19));
list.add(new Person("LiHua","9530",19));
TreeSet<Person> treeSet=new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int i = o1.getAge() - o2.getAge();
return i!=0?i:o1.getName().compareTo(o2.getName());
}
});
for (int i = 0; i < list.size(); i++) {
treeSet.add(list.get(i));
}
for (Person person : treeSet) {
System.out.println(person);
}
System.out.println("年龄最大的是:"+treeSet.last());
}
}
第二种,可以使用Collections.sort()
package test3_31.t2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/*List对象中存放多个Person对象(此对象包含,名字,年龄、id)。
按Person的年龄从小到大排序,假设年龄相等的话再按名字的大小来排序。
求出年龄最大的那个学生信息。*/
public class test {
public static void main(String[] args) {
Person person1 = new Person(1, "zs", 23);
Person person2 = new Person(2, "ls", 24);
Person person3 = new Person(3, "ww", 21);
ArrayList<Person> people = new ArrayList<>();
people.add(person1);
people.add(person2);
people.add(person3);
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int i = o1.getAge() - o2.getAge();
return i!=0?i:o1.getName().compareTo(o2.getName());
}
});
for (Person person : people) {
System.out.println(person);
}
System.out.println("年龄最大的是:"+people.get(people.size()-1));
}
}