We know we can use
Collections.sort
to sort a list after all elements inserted.
But if elements are inserted once a time, maybe the SortedMap
is more effective?
Though, the SortedMap
lack the subList
method.
What I need is something like SortedMap
can effectively insert small amount of elements many times, and can always get a 1~1000 sublist top-down with a Comparator
interface.
Any Suggestion?
I think a SortedSet
is a NavigableSet
which in turn has methods like subSet
, tailSet
, headSet
, ceiling
and floor
for this kind of problems.
So you could do something like:
SortedSet<Integer> set = new TreeSet<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
SortedSet<Integer> subset = set.subSet(3,7);
System.out.println(subset); //[3,4,5,6]
Obviously you can create you TreeSet
with whatever Comparator
you want, and perform the searches in the order that you find more convenient.
Comparator<Integer> reverse = Collections.reverseOrder();
SortedSet<Integer> set = new TreeSet<>(reverse);
//same thing here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With