简体   繁体   中英

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. 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. 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.

Given that, why are you using a TreeSet in the first place? Do your elements have a natural ordering that the TreeSet leverages? If not why not just dump them all into an ArrayList and sort the ArrayList as necessary?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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