You can p̶o̶p̶ poll and p̶u̶s̶h̶ offer all the items in your queue until you complete the cycle on your queue. Here is an example:
Mail firstMail = mailbox.peek(); Mail currentMail = mailbox.pop(); while (true) { //a base condition to stop the loop Mail tempMail = mailbox.peek(); if (tempMail == null || tempMail.equals(firstMail)) { mailbox.offer(currentMail); break; } //if there nothing wrong with the current mail, then re add to mailbox if (!badNews(currentMail)) { mailbox.offer(currentMail); } currentMail = mailbox.poll(); }
Please note that this approach will only work if this code is executed in one thread and there is no other thread that removes items from this queue.
Perhaps you need to check if you really want to poll or take items from BlockingQueue. Similar offers and offers.
Additional Information:
- Java BlockingQueue take () vs poll ()
- LinkedBlockingQueue puts vs offer
Another less flawed approach is to use a temporary collection, not necessarily parallel, and keep the items that you still need in the queue. Here is an example run:
List<Mail> mailListTemp = new ArrayList<>(); while (mailbox.peek() != null) { Mail mail = mailbox.take(); if (!badNews(mail)) { mailListTemp.add(mail); } } for (Mail mail : mailListTemp) { mailbox.offer(mail); }
Luiggi Mendoza
source share