This question already has answers here:
How to iterate over a PriorityQueue?
(10 answers)
Closed 3 years ago.
I have configuration-elements put into a PriorityQueue. I am accessing the elements via
for (Element e : queue) {
...
}
This works well enough but after putting an additional configuration element into the queue, the ordering is disrupted. Even stranger, it depends on the sequence in which I enter the elements into the queue, whether sorting is correct or not.
Javadoc of PriorityQueue states
The Iterator is not guaranteed to traverse the elements of the priority queue in any particular order.
basically, a PriorityQueue cannot be used in a for-each construct if ordering is required.
Depending on the code in question, either use iterated queue.poll() calls or switch to another datastructure like List and sort this exlipcitly via Collections.sort().
As with the ordering being correct sometimes: You just got lucky at first.
Related
This question already has answers here:
is collections.sort method only used for List type of collections?
(7 answers)
Closed 6 years ago.
Why can't I Collections.sort my Set<MyType>? My code is below. When I use an ArrayListthis code works perfectly, but when I use any kind of Set, I get this error.
Set<Auto> set = new HashSet<Auto>();
set.add(auto1);
set.add(auto2);
set.add(auto3);
set.add(auto4);
set.add(auto5);
Collections.sort(set, new Comparator<Auto>() {
#Override
public int compare(Auto o1, Auto o2) {
return o1.getMarka().compareTo(o2.getMarka());
}
});
HashSet is not an ordered collection; in other words, it does not contain elements in a certain order.
You can see a HashSet as a bag that contains objects. When you stick your hand in and pull out objects one by one, you don't know in what order you get elements out. You can't sort elements in the bag - because the bag doesn't keep them in the order that you sorted them in.
The order of elements is lost; so sorting a HashSet has no effect (besides the fact that Collections.sort takes a List instead of a Set as Mureinik noticed, so your code doesn't even compile).
If you need the elements in the Set to be in a specific, defined order, then use a different Set implementation, for example TreeSet.
Sets don't have an order, so you cannot order them. As seen in the Javadoc, Collections#sort receives a List, not any Collection.
This question already has answers here:
The built-in iterator for java's PriorityQueue does not traverse the data structure in any particular order. Why?
(5 answers)
Closed 6 years ago.
I was learning Java and trying to learn priority queue in collections. I tried with below example from one website:
import java.util.*;
class S
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Rahul");
queue.add("Jai");
System.out.println("iterating the queue elements:");
Iterator<String> itr=queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
here results came is below:
Amit
Jai
Karan
Vijay
Rahul`
I was expecting the result as :
Amit
Vijay
Karan
Rahul
Jai
I am not able to understand how the result changes from my expectation and what type of normal or default priority is used.
In case i want to get the same result as per my expectation, what should i do using prioiryqueue?
Please help me.
Here i want the exact cause of default ordering in priority queue.
Quoting javadoc of PriorityQueue:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
As you can see, the ordering of the PriorityQueue doesn't matter when using iterator(). Now if you began to take values from the queue using poll(), you would get the values in lexicographical order, i.e. the natural order of String.
If you want a queue that returns items in insertion order, use a regular Queue implementation like LinkedList or ArrayDeque.
This question already has an answer here:
why the output of the Hashmap is arbitary, not in a specific order? why its sorting order gets change on insertion & deletion of new node?
(1 answer)
Closed 8 years ago.
Items displayed as unsorted
map.put("California", "Sacramento");
map.put("Oregon", "Salem");
map.put("Washington", "Olympia");
System.out.println(map);
map.put("Alaska", "Juneau");
System.out.println(map);
HashMaps in java aren't sorted!
HashMap makes absolutely no guarantees about the iteration order. It
can (and will) even change completely when new elements are added.
TreeMap will iterate according to the "natural ordering" of the keys
according to their compareTo() method (or an externally supplied
Comparator). Additionally, it implements the SortedMap interface,
which contains methods that depend on this sort order.
LinkedHashMap will iterate in the order in which the entries were put
into the map
I try it, my print is :
{California=Sacramento, Oregon=Salem, Washington=Olympia}
{California=Sacramento, Oregon=Salem, Washington=Olympia, Alaska=Juneau}
Alaska=Juneau is displayed at the end.
but TreeMap is order.print:
{Alaska=Juneau, California=Sacramento, Oregon=Salem, Washington=Olympia}
This question already has answers here:
When should I use a TreeMap over a PriorityQueue and vice versa?
(11 answers)
Closed 9 years ago.
I am trying to understand when to use the two data structures. As far as I have understood the PriorityQueue is also implemented as a tree as the documentation states that the average time for insert, remove and contains is O(log(n)). The TreeSet also provides the same time complexity. Plus both of them are unsynchorized implementation. And I can write comparator for them to act like min heap or max heap.
Can some one point out in what conditions I use these two sets?
When you want a queue, use a PriorityQueue. When you want a Set, use a TreeSet. A TreeSet has unique elements, and doesn't offer the API of a Queue. A Queue doesn't offer the API of a Set, and allows multiple equal elements.
This question already has answers here:
The built-in iterator for java's PriorityQueue does not traverse the data structure in any particular order. Why?
(5 answers)
Closed 7 years ago.
I am trying to use priority queue to keep an ordered list of integers. in a simple exaple like this:
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(3000);
queue.offer(1999);
queue.offer(999);
for(Integer i : queue)
System.out.println(i);
This prints
999
3000
1999
This is not what I am expecting considering natural odering.
I simply want to iterate without removing or adding through the queue (which serves as a sorted list) WITH ordering. Can I still do that in a simple manner?
PriorityQueue is a collection optimized for finding the tail or head value quickly, using a partially ordered tree structure called heap (look it up on wikipedia). If you pop the elements, they will be ordered. If you want to iterate, use for example a SortedSet instead, which also stores the elements sorted.
This is a very sneaky problem with PriorityQueue: to quote the Api
The Iterator provided in method iterator() is not guaranteed to
traverse the elements of the priority queue in any particular order.
If you need ordered traversal, consider using
Arrays.sort(pq.toArray()).
Use Poll instead to get the head which will be in order