13

I am looking for a data structure that behaves like a queue (it could be a queue implementation) but allows me to get multiple elements from the collection (example: the first 15 elements of the queue).

It would be very nice if it doesn't require new dependencies.

Is there anything like that?

The closer I got during my research was the BlockingQueue with the drainTo() method, but this is not what I need.

JSBach
  • 4,679
  • 8
  • 51
  • 98

1 Answers1

10

LinkedList implement queue, collection, and list.

You could poll for the head, or get a sublist for the first 15 elements, and then also removeRange to remove them.

I'd probably just poll 15 times as the sublist/removeRange are going to need to iterate over the elements somehow anyway, therefore the perfromance will be similar.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • I'm still thinking about this or calling the multiple times the queue.poll() as you have suggested earlier. The advantage of the queue.poll() is that I do not need to handle the case that the queue is smaller as the batch size and that I do not have to handle removing the elements manually. I am not sure which code looks better. I am running some performance tests at the moment – JSBach Jul 15 '15 at 08:51
  • @JSBach I imagine the performance difference would be negligble, look at the source of sublist and removeRange - i think must iterate over the elements. – NimChimpsky Jul 15 '15 at 08:52
  • Ok, cool. Actually the removeRange is protected, so I can't use it. I would have to call sublist(...).clear(). Anyway, I will iterate the poll 15 times. Thanks for your help, as soon as possible I will mark it as answer – JSBach Jul 15 '15 at 09:01
  • I agree with the suggestion of *LinkedList* as an implementation. But you should use interfaces as a type of your collections in order to simplify code maintenance. To respect the [*Queue*](http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html) interface, there is the [*Deque*](http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html) subinterface that provides the ability to go back to the first element (and by the way retrieve the 15 first elements). *LinkedList* is an implementation of that interface. – bdulac Jul 30 '15 at 16:31