5

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?

rufushuang
  • 302
  • 4
  • 17
  • this [question](http://stackoverflow.com/questions/8725387/why-is-there-no-sortedlist-in-java) could help you probably. – senseiwu Apr 25 '16 at 06:22
  • @zencv the question doesn't mention the `subList`, that exactly what i need – rufushuang Apr 25 '16 at 06:25
  • Doesn't `NavigableSet` support those kind of subviews? I think methods like `NavigableSet.subSet(start,end)` could probably work here. – Edwin Dalorzo Jun 21 '16 at 18:41

1 Answers1

1

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
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • This is a WRONG answer. All subset/tail/head... and Comparator are VALUE-BASED, not COUNT-BASED. – rufushuang Jun 23 '16 at 07:16
  • @rufushuang A much better comment would have been: "Edwin, since comparators are value-based, as are all the methods you suggested, how do you think I could get a constant range of elements out of the set then"?. You can see that my style of comment would have encouraged me to come back and try to improve or correct my answer. You can catch more flies with honey than you do with vinegar. – Edwin Dalorzo Jun 23 '16 at 14:47