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

Java list对象列表排序 实例

时间:2014-11-14 20:58:25      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   java   for   div   

package com.test;

public class Bean {

    private String name;
    private int priority;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

}
package com.test;

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

public class Test {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) {

        List<Bean> list = new ArrayList<Bean>();
        for (int i = 1; i < 10; i++) {
            Bean bean = new Bean();
            bean.setName("name_" + i);
            bean.setPriority(new Random().nextInt(10));
            list.add(bean);
        }
        // 打印
        for (Bean b : list) {
            System.out.println(b.getPriority() + "|" + b.getName());
        }

        Collections.sort(list, new Comparator() {
            public int compare(Object a, Object b) {
                int one = ((Bean) a).getPriority();
                int two = ((Bean) b).getPriority();
                return one - two;
            }
        });
        System.out.println("--------------------------------");
        // 打印
        for (Bean b : list) {
            System.out.println(b.getPriority() + "|" + b.getName());
        }
    }

}

 

Java list对象列表排序 实例

标签:style   blog   io   color   ar   sp   java   for   div   

原文地址:http://www.cnblogs.com/qqzy168/p/4098031.html

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