Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sorted collection with a count-based sublist

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?

like image 221
rufushuang Avatar asked Nov 08 '22 16:11

rufushuang


1 Answers

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
like image 124
Edwin Dalorzo Avatar answered Nov 14 '22 21:11

Edwin Dalorzo