I have a streaming time series, of which I am interested in keeping the last 4 elements, which means I want to be able to pop the first, and add to the end. Which Java Collection is the best for this? Vector ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Consider CircularFifoBuffer from Apache Common.Collections. Unlike Queue you don't have to maintain the limited size of underlying collection and wrap it once you hit the limit.
CircularFifoBuffer will do this for you because of the following properties:
However you should consider it's limitations as well - for example, you can't add missing timeseries to this collection becaue it doens't allow nulls.
If you need
then you can use this CircularArrayList for Java in this way (for example):
All these methods run in O(1).
None of the previously given examples were meeting my needs completely, so I wrote my own queue that allows following functionality: iteration, index access, indexOf, lastIndexOf, get first, get last, offer, remaining capacity, expand capacity, dequeue last, dequeue first, enqueue / add element, dequeue / remove element, subQueueCopy, subArrayCopy, toArray, snapshot, basics like size, remove or contains.
EjectingQueue
EjectingIntQueue
Since Guava 15.0 (released September 2013) there's EvictingQueue:
Example use:
Since Java 1.6, there is
ArrayDeque
, which implementsQueue
and seems to be faster and more memory efficient than aLinkedList
and doesn't have the thread synchronization overhead of theArrayBlockingQueue
: from the API docs: "This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue."Use a Queue
There's five simple methods of a Queue
element() -- Retrieves, but does not remove, the head of this queue.
offer(E o) -- Inserts the specified element into this queue, if
possible.
peek() -- Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
poll() -- Retrieves and removes the head of this queue, or null if this queue is empty.