I'm a beginner in Java. Please suggest which collection(s) can/should be used for maintaining a sorted list in Java. I have tried Map
and Set
, but they weren't what I was looking for.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
- StackExchange API - Deserialize Date in JSON Respo
Use Google Guava's TreeMultiset class. Guava has a spectacular collections API.
One problem with providing an implementation of List that maintains sorted order is the promise made in the JavaDocs of the
add()
method.The problem with PriorityQueue is that it's backed up by an simple array, and the logic that gets the elements in order is done by the "queue[2*n+1] and queue[2*(n+1)]" thingie. It works great if you just pull from head, but makes it useless if you are trying to call the .toArray on it at some point.
I go around this problem by using com.google.common.collect.TreeMultimap, but I supply a custom Comparator for the values, wrapped in an Ordering, that never returns 0.
ex. for Double:
This way I get the values in order when I call .toArray(), and also have duplicates.
There are a few options. I'd suggest TreeSet if you don't want duplicates and the objects you're inserting are comparable.
You can also use the static methods of the Collections class to do this.
See Collections#sort(java.util.List) and TreeSet for more info.
This comes very late, but there is a class in the JDK just for the purpose of having a sorted list. It is named (somewhat out of order with the other
Sorted*
interfaces) "java.util.PriorityQueue
". It can sort eitherComparable<?>
s or using aComparator
.The difference with a
List
sorted usingCollections.sort(...)
is that this will maintain a partial order at all times, with O(log(n)) insertion performance, by using a heap data structure, whereas inserting in a sortedArrayList
will be O(n) (i.e., using binary search and move).However, unlike a
List
,PriorityQueue
does not support indexed access (get(5)
), the only way to access items in a heap is to take them out, one at a time (thus the namePriorityQueue
).You want the SortedSet implementations, namely TreeSet.
TreeSet would not work because they do not allow duplicates plus they do not provide method to fetch element at specific position. PriorityQueue would not work because it does not allow fetching elements at specific position which is a basic requirement for a list. I think you need to implement your own algorithm to maintain a sorted list in Java with O(logn) insert time, unless you do not need duplicates. Maybe a solution could be using a TreeMap where the key is a subclass of the item overriding the equals method so that duplicates are allowed.