当前位置:   article > 正文

集合案例--对ArrayList容器中的内容进行排序

7-1 容器-arraylist-排序
package com.Set;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ArrayListDemo4 {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person("jak", 20));
        list.add(new Person("roos", 10));
        list.add(new Person("marry", 30));
        list.add(new Person("jack", 20));
        Collections.sort(list, new Comparator<Person>() {

            @Override
            public int compare(Person o1, Person o2) {
                if (o1.getAge() - o2.getAge() > 0) {
                    return 1;
                } else if (o1.getAge() - o2.getAge() < 0) {
                    return -1;
                }
                return o1.getName().compareTo(o2.getName());
            }

        });
        for(Person p:list) {
            System.out.println(p.getAge()+p.getName());
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        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;
    }

}

 

转载于:https://www.cnblogs.com/tanlei-sxs/p/9991872.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/715606
推荐阅读
相关标签
  

闽ICP备14008679号