Reputation: 85
What is the best way to keep a list of items that is sortable and searchable? I want to have a list of medication-indications that I want to keep in order like this:
Medication --------- Indication
lisinopril --------- hypertension
amlodipine besylate --------- hypertension
amlodipine besylate --------- coronary artery disease (cad)
carvedilol --------- hypertension
ciprofloxacin --------- skin and skin structure infections
ciprofloxacin --------- bone and joint infections
No matter what order, amlodipine besylate HAS to match hypertension. I need to be able to sort alphabetically. Then I need to be able to get subsets. So I need to be able to pull the indications for say ciprofloxacin and lisinopril and then search to see if hypertension is in that resulting list.
How can I do this? I have it currently as two separate hash sets.
Upvotes: 2
Views: 108
Reputation: 85
Thank you everyone! After a bit of experimentation with each of the suggestions, I was able to determine that a TreeMap was indeed the best solution. Since the treeMap contains Key-Value pairs, the Key in both maps serves as the "link" to maintain the relationship. Just make sure that if you add or delete an item from one Map you have to do the same to the corresponding Key in the other map.
Upvotes: 0
Reputation: 61
Try using TreeMap
Upvotes: 1
Reputation: 162
Use B+ tree. It is default sorted and efficient searches.
Insertion however may need loops to keep it balanced.
Upvotes: 0
Reputation: 503
The SortedSet interface provides functionalities to keep the elements sorted. And the NavigableSet interface provides functionalities to navigate through the SortedSet.
Since the TreeSet class implements NavigableSet interface, it has the functionalities of both - the NavigableSet as well as the SortedSet. The TreeSet uses a self-balancing binary search tree, more specifically a Red-Black tree.
The contains() method is used to check if a given element is present in a given TreeSet. If the element is found, it returns true, otherwise false.
Upvotes: 0
Reputation: 15696
TreeSet is a sorted set of items:
A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
For searching, filtering, mapping, subset creation etc. I recommend using the Java Stream API.
Upvotes: 0
Reputation: 235984
Although it's a tree not a list, a TreeSet
meets the requirements of being sorted, efficiently O(log(n))
searchable and you can get subsets out of it. It'll be better if you declare it as a SortedSet
.
Upvotes: 2