简体   繁体   English

从具有不同排序标准的树集中获取元素的有效方法

[英]Efficient way to get elements out of a treeset with different sorting criteria

I have a treeset containing student objects(name, roll number, address and age) and are stored in ascending order of their names and if the names are same, then roll numbers. 我有一个包含学生对象(名称,卷编号,地址和年龄)的树集,并按其名称的升序存储,如果名称相同,则卷编号。 This list is coming from a file and could get really big. 此列表来自文件,可能会变得很大。

Now i have to provide a way to display the list that could be in any order - sorted in ascending/descending order according to name, age, address or roll number. 现在,我必须提供一种显示列表的方式,该列表可以按任何顺序-根据名称,年龄,地址或卷号以升序/降序排序。 I am looking for an efficient solution for my problem. 我正在寻找解决我问题的有效方法。

What i am thinking of doing is to take a temporary arraylist and get the elements into it in the order i want. 我正在考虑做的是获取一个临时arraylist并按我想要的顺序将元素放入其中。 But for this i will have to implement a different method for every criteria and this looks inefficient to me. 但是为此,我将不得不为每个标准实施不同的方法,这对我而言似乎效率很低。

Is there any way i can get the elements in the treeset out in the way i want into an array coz i just need to print the values and destroy the temp list afterwards 有什么办法可以让树集中的元素以我想要进入数组的方式,因为我只需要打印值并随后销毁临时列表即可

The only way to do it is, as you said, iterating over the tree and pulling out all of the matching elements into an ArrayList. 如您所说,唯一的方法是遍历树并将所有匹配的元素拉出到ArrayList中。 Once you've done that you can sort based on a particular Comparator. 完成后,您可以根据特定的比较器进行排序。

If you just want to pull out elements based on the natural ordering, you can use the subset method, but that depends on the compareTo method in the tree, which is not valid for all the different searches that you want to do. 如果只想根据自然顺序提取元素,则可以使用子集方法,但这取决于树中的compareTo方法,该方法对于要执行的所有不同搜索均无效。

Given that, why are you using a TreeSet in the first place? 鉴于此,为什么首先要使用TreeSet? Do your elements have a natural ordering that the TreeSet leverages? 您的元素是否具有TreeSet可利用的自然顺序? If not why not just dump them all into an ArrayList and sort the ArrayList as necessary? 如果不是,为什么不将它们全部转储到ArrayList中,并根据需要对ArrayList进行排序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM