FIFO based Queue implementations? - java

I need a simple FIFO implemented queue for storing a bunch of ints (I don't mind much if it is generics implementation).
Anything already baked for me in java.util or Trove/Guava library?

Yeah. Queue
LinkedList being the most trivial concrete implementation.

Here is example code for usage of java's built-in FIFO queue:
public static void main(String[] args) {
Queue<Integer> myQ = new LinkedList<Integer>();
myQ.add(1);
myQ.add(6);
myQ.add(3);
System.out.println(myQ); // 1 6 3
int first = myQ.poll(); // retrieve and remove the first element
System.out.println(first); // 1
System.out.println(myQ); // 6 3
}

ArrayDeque is probably the fastest object-based queue in the JDK; Trove has the TIntQueue interface, but I don't know where its implementations live.

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :
#Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
1
2
Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.
So this is a Queue only if used in conjunction with add.
Try this :
#Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.push(1);
queue.push(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
2
1

Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.
For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.
For details about method with sample example you can refer FIFO based Queue implementation in Java.
PS: Above link goes to my personal blog that has additional details on this.

Related

The order of the PriorityQueue is wrong

I meet a problem about order of PriorityQueue in Java 8, Intellij Idea, when I add the third number in the queue, the order is wrong, but only the third one have this problem, here is my code.
import java.util.*;
public class vector {
static Queue<Integer> q=new PriorityQueue<Integer>();
public static void addNum(int num) {
q.add(num);
}
public static void main(String args[]) {
addNum(-1);
addNum(-2);
addNum(-3);
addNum(-4);
addNum(-5);
}
}
I try to debug the code, after addNum(-3), the queue is -3,-1,-2, but after addNum(-4), the queue is -4, -3, -2, -1.
The contract for PriorityQueue does not guarantee iteration order, but rather it guarantees that each element removed from the priority queue will follow either the natural ordering of the queue's type, or the ordering of a custom comparator, should one be provided.
The Javadoc comments on what you are seeing:
Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out).
The contract which Java appears to enforce for priority queues is that the first element removed from the queue will follow the natural order of the object in the queue, or using a custom comparator, should one be provided.
If we add to your current script to remove the five elements added, we will see that the items returned will be ordered from least to greatest:
public static void main(String args[]) {
addNum(-1);
addNum(-2);
addNum(-3);
addNum(-4);
addNum(-5);
// now remove all elements
while (!q.isEmpty()) {
System.out.println(q.remove());
}
}
This prints:
-5
-4
-3
-2
-1
If you need a collection which maintains sorting order, then consider using something like TreeSet. Or, you could use a regular ArrayList, and then call Collections.sort() if you want to impose a certain order.
PriorityQueue's implementation is a priority heap implementation & not sorted list.
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any specific order. If you need ordered traversal, use something like:
Arrays.sort(q.toArray());
for (Integer data :q) {
System.out.println(data);
}
As other answers implied, you should use queue.poll() if you want to retrieve the elements in the right order, as in:
List<E> entities = new ArrayList<>();
while(!queue.isEmpty()){
entities.add(queue.poll());
}
The order of entities in the entities list will be as expected.
Rationale: Java PriorityQueue only ensures the order of enqueuing of the entities, not the order of iteration in an underlying collection.
The entities are mapped onto an underlying collection "unsorted", meaning if you try to access the entities using a stream:
queue.stream().collect(Collectors.toList());
or an iterator:
Iterator<E> i = queue.iterator();
...
E e = i.next()
or any other method, such as queue.forEach(), or in fact observe your queue in a IDE debugger, there is no guarantee as to the order of the entries in the collections obtained using any of these methods.
This the most Common Question, Many Collection Frame Work like ArrayList, LinkedList, and furthermore but In PriorityQueue, when you are printing the elements it will be in the Sorted Order and that order is followed MIN_HEAP property or
Basically, we can say that the Priority Queue is implemented on Min Heap Property.
So First Understand the MinHeap then implement the code.

Working With Stack

it has been to long since i asked here ..
I have this homework which has this Q Remove The Bottom Of The Stack I did it
good but not great ..
but now i have a Q is how to reverse the stack i did it by using another stack
is there a better way
this is what i did :
public static<T> void removeLast(LinkedList<T> st)
{
LinkedList<T> store = new LinkedList<>();
while (!st.eamty()){
store.push(st.pop());
}
store.pop();
while(!store.eamty()){
st.push(store.pop());
}
}
some src I found
Most efficient way to reverse a stack and add to an ArrayList
https://www.careercup.com/question?id=12689669
I'd made the following instead:
public static<T> void removeLast(LinkedList<T> st)
{
return st.removeLast();
}
But this is not a queue meant to be used and is also quite "expensive" operation ...
First of all, LinkedList<T> is not just a Stack. It is a List. In fact, it is a list class with a specific operation to removing the last element. (The removeLast method is defined by the Deque interface which LinkedList implements. The Deque abstraction is a "double ended queue"; i.e. something that can act as both a FIFO and a LIFO - a queue and a stack.)
So if you are able to the fact that this representation of a stack is implemented as a linked list, then the solution is to call that method.
On the other hand, if you are required / restricted to implementing your removeLast using only "stack-like" methods in the LinkedList API, then your approach of popping all elements to a temporary stack is probably as good as you can get.

How to add an element in front of Queue in java?

I am using Queue<T> q1 and I know that an element will be added using q1.offer(); at the end of the queue. But now, what I want to do is add an element in front of queue, which is not possible with Queue. The possible methods I could think of are
Use of double ended queue and I can add the elements in front and at the end.
reverse the q1, add the element at the end of the queue and reverse again.
Now, as a non-programmer guy, I am not sure, how to code these methods; which one is more economical and easier to do.
Problems I faced in 1) is transform of existing Queue to Deque and vice versa; and in 2) How to use Collections.reverseOrder(); to reverse the existing Queue.
The following is the way to add elements to the first of queue using deque and asLifoQueue method in collections.this will arrange the elements in last in first out order...
public class Practice15 {
public static void main(String[] args) {
Deque<Integer> dd=new ArrayDeque<Integer>();
dd.offerFirst(123);
dd.offerFirst(258);
dd.offerFirst(125);
System.out.println(dd);
Queue<Integer> q1=Collections.asLifoQueue(dd);
System.out.println(q1);
}
}
If you have to insert an element at the front, a Queue is definitely not the solution. Go for a double ended queue.
If you use "Queue q1" - that is only a declaration of variable q1, while Queue itself is only an interface. Are you probably looking to work with some implementation of Queue?
Check out Java API: http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html)

What's the Java equivalent of C++'s STL Queue?

I was browsing through the Java docs to look for the Java equivalent for C++'s STL Queue, but all I found was an interface called Queue and a bunch of implementations I can't make heads or tails of.
Does Java have an implementation for Queue that's just a FIFO data structure without the added bells and whistles? I only need the enqueue, dequeue and front operations and the data structure should allow duplicates.
Queue will work. Use any implementation you like. LinkedList or ConcurrentLinkedQueue for example.
enqueue = offer(..)
dequeue = poll()
front = peek()
That docs page lists all the classes that implement the interface. So, for instance, you can do the following (DISCLAIMER: hasn't been near a compiler):
Queue<E> q = new LinkedList<E>();
E x1 = new E();
E x2 = new E();
E x3;
q.offer(x1);
q.offer(x2);
x3 = q.poll();
You can just use LinkedList. Sure, it has lots of functionality you don't need, but it's not hurting you either.
The java.util.LinkedList class is probably what you want, and the methods would be "add", "remove", and "element".
What you're probably looking for is a double-ended queue. See the Deque interface and it's implementing classes.

A fast queue in Java

I am looking for a fast queue implementation in Java. I see that LinkedList implements the Queue interface, but it will only be as fast as a LinkedList right? Is there a way to have a queue that will be faster especially for add (I only need poll, add and check for empty).
Down the line I may also need a PriorityQueue but not yet.
If multiple threads are going to be accessing the queue then consider using an ArrayBlockingQueue. Otherwise take a look at ArrayDeque. From the ArrayDeque API:
This class is likely to be faster than
Stack when used as a stack, and faster
than LinkedList when used as a queue.
Specifically an array-based queue implementation reduces the need to resize the underlying array if the existing array has sufficient capacity, thus making additions to the queue generally faster than LinkedList. Be aware that ArrayBlockingQueue is a bounded implementation whereas ArrayDeque will resize as required.
The flip-side is that LinkedList will typically provide a much more compact representation, particularly in cases where your queue grows and shrinks by a large amount. For example, if you added 10,000,000 elements to an ArrayDeque and then removed 9,999,999 elements, the underlying array would still be of length 10,000,000 whereas a LinkedList would not suffer from this problem.
In reality, for single-threaded access to a non-blocking queue I tend to favour LinkedList. I imagine the performance differences are so negligable you wouldn't notice the difference anyway.
I see that LinkedList implements the Queue interface, but it will only be as fast as a LinkedList right?
Eyeballing the source code, LinkedList is O(1) for Queue.add, Queue.poll, and Queue.peek operations.
I hope that's fast enough.
If performance of a linked list was really a problem, an alternative would be to implement a "circular queue" in an array, i.e. a queue where the start and end point move as entries are added and deleted. I can give more details if you care. When I was using languages that did not have a library of collections, this was how I always implemented queues because it was easier to write than a linked list and it was faster. But with built-in collections, the effort of writing and debugging my own collection for a special case is not worth the trouble 99% of the time: When it's already written, the fact that I could write it a different way faster than I could re-write it the way Java does is pretty much an irrelevant fact. And any performance gain is likely to be too small to be worth the trouble. I sub-type existing collections to get special behavior I need now and then, but I'm hard-pressed to think of the last time that I wrote one from scratch.
You may want to have a look at https://dzone.com/articles/gaplist-lightning-fast-list which introduces GapList. This new list implementation combines the strengths of both ArrayList and LinkedList.
It therefore implements the Deque interface, but can also be presized like the above mentioned ArrayDeque. In addition, you also get all the possibilities of the List interface for free. Get it at https://github.com/magicwerk/brownies-collections.
Start with really simplistic rotating Queue implementation with "C/C++ like" attitude and fixed size.
class SimpleQueue<E>
{
int index = 0;
int head = 0;
int size = 100;
int counter = 0;
E[] data ;
#SuppressWarnings("unchecked")
SimpleQueue()
{
data = (E[]) new Object[size];
}
public void add(E e)
{
data[index]=e;
index=(index+1)%size;
counter++;
}
public E poll()
{
E value = data[head];
head=(head+1)%size;
counter--;
return value;
}
public boolean empty()
{ return counter==0; }
//Test
public static void main(String[] args)
{
SimpleQueue<Integer> s = new SimpleQueue<Integer>();
System.out.println(s.empty());
for(int i=0; i< 10; i++)
s.add(i);
System.out.println(s.empty());
for(int i=0; i<10; i++)
System.out.print(s.poll()+",");
System.out.println("\n"+s.empty());
}
}
And then improve it.

Categories