I have a list of items sorted using Collections.sort based on two properties
item name and price. With price taking higher priority. Now, if I want to insert an element
into an already sorted list of elements, I could write a manual binary search and find where to insert it so that the resulting list remains sorted.
Is there an easier way to achieve the same using some inbuilt methods in Java?
Asked
Active
Viewed 46 times
0

pensee
- 375
- 1
- 10
-
You could use a [`TreeSet`](https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html). – Olivier Jun 19 '22 at 08:21
-
There is [`Collections.binarySearch`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Collections.html#binarySearch%28java.util.List,T,java.util.Comparator%29). It returns a negative number encoding the insertion point if the element is not in the `List`. Pass your own `Comparator` to it, something like that `Comparator.comparingDouble(Item::getPrice).thenComparing(Item::getName)`. – Johannes Kuhn Jun 19 '22 at 08:51
1 Answers
0
Ideally you want to use a data structure that's based on something meant for keeping items in order while you add/remove items. Those based on (balanced) binary search trees do that - examples in the Collections framework are TreeSet
and TreeMap
.

ndc85430
- 1,395
- 3
- 11
- 17
-
TreeSet seems good. There is no need for manual binary search or even the Collections.binarySearch, especially for insertion, will automatically take care of it. – pensee Jun 21 '22 at 15:06
-