请赏脸~
- package cn.liweidan.test1;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- /**
- * 把集合中存储多个Person对象,Person有姓名和年龄,找出年龄最大的
- *
- * @author Weidan
- *
- */
- public class Demo04 {
- public static void main(String[] args) {
- //创建对象
- Person p1 = new Person("张三",20);
- Person p2 = new Person("李四",20);
- Person p3 = new Person("王五",80);
- //创建容器
- List<Person> list = new ArrayList<>();
- list.add(p1);
- list.add(p2);
- list.add(p3);
- //按照排序类进行排序 年龄最大的会被排在最后一个元素
- Collections.sort(list,new PaiXu());
- //取出最后一个元素 输出
- Person p = list.get(list.size()-1);
- System.out.println(p.toString());
- }
- }
- /**
- * Person类 包含名字和年龄
- * @author Weidan
- *
- */
- class Person {
- private String name;
- private int age;
- public Person() {
- // TODO Auto-generated constructor stub
- }
- public Person(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return "Person [name=" + name + ", age=" + age + "]";
- }
- }
- /**
- * 排序类
- * 先按照年龄排列再按照名字排列
- * @author Weidan
- *
- */
- class PaiXu implements Comparator<Person> {
- @Override
- public int compare(Person o1, Person o2) {
- if(o1.getAge()<o2.getAge()){
- return -1;
- }else if(o1.getAge()>o2.getAge()){
- return 1;
- }else{
- if(0!=o1.getName().compareTo(o2.getName())){
- return -1;
- }else if(o1.getName().compareTo(o2.getName())>0) {
- return 1;
- }else{
- return 0;
- }
- }
- }
- }
复制代码 |