Java:Collection.sort()vs排序集vs PriorityQueue [英] Java: Collection.sort() vs Sorted Set vs PriorityQueue

查看:170
本文介绍了Java:Collection.sort()vs排序集vs PriorityQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:MyObject列表列表, 和比较器,用于比较2个MyObjects

I have the following structures: list of lists of MyObject, and comparator that compares 2 MyObjects

任务是从列表中获取最多N个较小的对象.

The task is to get up to N lesser objects from the list.

可以通过以下几种方法解决该问题:

The problem may be solved by several ways:

  1. 将所有元素放在一个新列表中并使用 Collections.sort()或Arrays.parallelSort()

  1. To put all elements in one new list and to sort it using Collections.sort() or Arrays.parallelSort()

要将所有元素放入ProirityQueue中,然后检索N个最重要的元素

To put all elements into ProirityQueue and then retrive N top elements

将所有元素放入SortedSet(TreeSet)中并检索所需的元素 使用迭代器

To put all elements in SortedSet (TreeSet) and retrieve needed elements using iterator

我不知道选择哪种方式.准则是绩效. 内部列表"的大小约为20个元素,外部"列表的大小约为10

I don't know wich way to choice. The creteria is performance. The size of "internal list" is about 20 elements and "outer" list size is about 10

推荐答案

如果您只希望N个元素中最小的200个元素,而N很小(例如10-20),那么为什么还要麻烦将所有元素添加到另一个元素中结构(是列表还是PriorityQueue)?只需创建一个包含N个项目的数组(如果需要,则创建一个List).遍历列表列表中的每个元素,然后将元素插入N数组中的正确位置.丢弃从列表底部掉落的第N个元素.这就像一个插入排序算法,但只执行部分排序.

If you only want the lowest N elements out of about 200, and N is small (say 10-20) then why would you bother adding all elements to another structure (be it a list or PriorityQueue)? Just create an array (or a List if you must) of N items. Go through every element in the list of lists, and insert the element into the correct rank in the array of N. Discard the Nth element which gets dropped off the bottom of the list. This is like an Insertion Sort algorithm but only doing a partial sort.

如果N大(例如,在200个项目中占150个),则使用完整排序或PriorityQueue可能会更好.您需要进行测量.

If N is large (say 150 out of your total of 200 items) then a full sort or PriorityQueue might be better. You'll need to measure.

这篇关于Java:Collection.sort()vs排序集vs PriorityQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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