码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-11-20 23:03:44      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:int   imp   import   class   tde   get   package   arraylist   style   

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;
    }

}

 

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

标签:int   imp   import   class   tde   get   package   arraylist   style   

原文地址:https://www.cnblogs.com/tanlei-sxs/p/9991872.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!