Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Java
|
PriorityQueue
Notes
Example
Example: Comparator
Notes
Objects must implement java.lang.Comparable<T> (Exception: cannot be cast to java.lang.Comparable)
Ordered collection (java.lang.Comparable<T>)
null elements not allowed
Duplicates elements allowed
Example
PriorityQueue<String> pq = new PriorityQueue<>(); // pq.add(null); // java.lang.NullPointerException pq.add("c"); pq.add("bb"); pq.add("bb"); pq.add("aaa"); pq.add("aaa"); pq.add("aaa"); while (!pq.isEmpty()) System.out.println(pq.remove()); // pq.forEach(System.out::println); // elements of the queue might be printed in a random order
Output:
aaa aaa aaa bb bb c
Example: Comparator
PriorityQueue<String> pq = new PriorityQueue<>(Comparator.comparing(String::length)); // pq.add(null); // java.lang.NullPointerException pq.add("c"); pq.add("bb"); pq.add("bb"); pq.add("aaa"); pq.add("aaa"); pq.add("aaa"); while (!pq.isEmpty()) System.out.println(pq.remove()); // pq.forEach(System.out::println); // elements of the queue might be printed in a random order
Output:
c bb bb aaa aaa aaa
© 2010-2022
mti
tek