基于 Id 对对象数组列表进行桶排序或排序? [英] Bucket Sorting or sorting an arraylist of objects based on Id?

查看:35
本文介绍了基于 Id 对对象数组列表进行桶排序或排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过桶排序.任何人都可以澄清当我们对数百万条记录进行排序时它如何提供最佳性能吗?有没有n*log(n)O(n) 的算法?

I've heard about the Bucket Sorting. Could any one clarify how it gives the best performance when we sort millions of records? Is there any algorithm with n*log(n) or O(n) ?

我有 1000 个员工对象,每个员工对象都有 id、name、salary 属性.我将这些对象添加到 ArrayList 我想根据 id 属性对这些对象进行sort.反正有吗?不使用 Collections.sort() 方法.考虑以下解决方案,请任何人帮助哪一个提供最佳性能?

I have 1000 employee objects each employee object has id, name, salary properties. I added these objects to ArrayList I want to sort these objects based on id property. Is there anyway? With out using Collections.sort() method. Considered below solutions, please anybody help which one gives best performance?

谢谢

推荐答案

Without Collections.sort() :

首先在 Empoloyee 的类中实现 Comparable 并覆盖 compareTo

First implement Comparable<Employee> in Empoloyee's class and override compareTo

@Override
public int compareTo(Employee o) {

    return this.id.compareTo(o.id);
}

将您的未排序列表传递给 TreeSet 并获取 set(按 id 排序)然后使用此 set 创建 new List代码>

Pass your unsorted list to TreeSet and get set(sorted on id) then create new List with this set

List<Employee> list=new ArrayList<Employee>();
    list.add(new Employee(1, "A", Double.parseDouble("50")));
    list.add(new Employee(22, "B", Double.parseDouble("11")));
    list.add(new Employee(3, "C", Double.parseDouble("222")));
    list.add(new Employee(34, "D", Double.parseDouble("4")));

    SortedSet<Employee> set=new TreeSet<Employee>( list);

    List<Employee> l=new ArrayList<Employee>();
    l.addAll(set);

    System.out.println(l);

OutPut:按 id 排序,没有Collections.sort()

OutPut: Sorted on id withoutCollections.sort()

[Employee [id=1, name=A, price=50.0], Employee [id=3, name=C, price=222.0], Employee [id=22, name=B, price=11.0], Employee [id=34, name=D, price=4.0]]

员工类:

class Employee implements Comparable<Employee>{

Integer id;
String name;
Double price;
       -------

}

这篇关于基于 Id 对对象数组列表进行桶排序或排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆