Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collection for special scrolling, circular queue

I'm looking for something similar to ConcurrentLinkedQueue, but with the following behaviors:

  • When I peek()/poll() the queue, it retrieves the HEAD, does not remove it, and then subsequently advances the HEAD one node towards the TAIL
  • When the HEAD == TAIL, the next time I peek()/poll(), the HEAD is reset to its original node (thus "circular" behaviour)

So if I created the queue like so:

MysteryQueue<String> queue = new MysteryQueue<String>();
queue.add("A"); // The "original" HEAD
queue.add("B");
queue.add("C");
queue.add("D"); // TAIL

String str1 = queue.peek(); // Should be "A"
String str2 = queue.peek(); // Should be "B"
String str3 = queue.peek(); // Should be "C"
String str4 = queue.peek(); // Should be "D"
String str5 = queue.peek(); // Should be "A" again

In this fashion, I can peek/poll all day long, and the queue will just keep scrolling through my queue, over and over again.

Does the JRE ship with anything like this? If not, perhaps something in Apache Commons Collections, or some other third party lib?

like image 578
IAmYourFaja Avatar asked Mar 22 '23 15:03

IAmYourFaja


1 Answers

I don't think it exists in the JRE.

How about Google Guava's Iterables.cycle?

Something like this:

// items can be any type of java.lang.Iterable<T>
List<String> items = Lists.newArrayList("A", "B", "C", "D");
for(String item : Iterables.cycle(items)) {
    System.out.print(item);
}

will output

A B C D A B C D A B C D ...
like image 191
wjans Avatar answered Apr 07 '23 13:04

wjans