Java list对象列表排序 实例

Posted liness0713

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java list对象列表排序 实例相关的知识,希望对你有一定的参考价值。

http://www.cnblogs.com/qqzy168/p/4098031.html

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对象列表排序 实例的主要内容,如果未能解决你的问题,请参考以下文章

java中List对象列表去重或取出以及排序

Python入门题045:根据对象属性进行排序

Python中元祖对象排序

Java 8:按属性对对象列表进行排序,无需自定义比较器

Java8使用Stream流实现List列表的查询统计排序分组

java 如何对对象进行排序