12

Possible Duplicate:
sorted collection in java

I'm wondering if there is a built-in class in Java that lets me add elements that are automatically sorted. Sorting should preserve add order if two elements are ranked the same. I think it would be like a priority queue but shouldn't "pop" the elements, I want them to stay in the list.

Obviously I could implement this myself but I'd rather use something implemented in the Java language (less bug testing / would be good to know for future projects too instead of importing my own code).

I would also be interested in third party source if there isn't anything like this in the language.

Community
  • 1
  • 1
Ciph3rzer0
  • 567
  • 2
  • 4
  • 15
  • possible duplicate of [sorted collection in java](http://stackoverflow.com/questions/416266/sorted-collection-in-java) see also http://stackoverflow.com/questions/2661065/a-good-sorted-list-for-java – Matt Ball Aug 17 '11 at 18:58
  • Java "maps" are auto-sorted, and have extremely fast lookup. You could, of course, have a queue of maps. A more sophisticated approach might be to use a TreeMap; a simpler approach might be to call .sort() on a vanilla ArrayList. Lots and lots of possibilties anywhere along the spectrum... – paulsm4 Aug 17 '11 at 19:00
  • 1
    @paulsm4: `Map` usually _isn't_ sorted in Java, `SortedMap` implementations are. – merryprankster Aug 17 '11 at 19:02
  • @paulsm4 Java `Map` doesn't not require implementations to sort (such as `HashMap`). – Steve Kuo Aug 17 '11 at 19:02

1 Answers1

13

It seems SortedList this would work

This class implements a sorted list. It is constructed with a comparator that can compare two objects and sort objects accordingly. When you add an object to the list, it is inserted in the correct place. Object that are equal according to the comparator, will be in the list in the order that they were added to this list. Add only objects that the comparator can compare.

jmj
  • 237,923
  • 42
  • 401
  • 438