如何根据类别从列表(复杂数据类型)中获取前10个记录?

时间:2016-09-29 06:23:48

标签: java list collections

我有一个班级结构:

class TopTenAccount{
    Long account;
    Long src;
    Long dest;
    Long count;
}

我有这个对象的列表。

List<TopTenAccount> topTenAccount;

现在基于计数我想要只有10条记录(标准:&#34;帐户+ src + dest&#34;每条记录应该相同)。

基本上我想要为每个类别(帐号+ src + dest)排名前10。

2 个答案:

答案 0 :(得分:1)

将Collections.sort与自定义比较器一起使用

                   Collections.sort(list,new Comapartor<TopTenAccount> {
      //override compateTo method with your compare logic

        });

然后进行循环并获取此列表中的前10个对象

        for(int i=0;i<10 && i < list.size();i++) {
             System.out.println(list.get(i));
        }

答案 1 :(得分:0)

根据计数字段使用自定义排序。如果那就是你需要的东西

topTenAccount.sort((x,y)=>{
int temp = x.count - y.count;
if(temp!=0)
return temp;
});

这将按升序基于 count 对集合进行排序。下一步是循环并获取集合中的第一个/最后10个项目。