Monday, November 18, 2013

Java PriorityQueue Example

Write a program that creates and prints a priority queue of some country names in descending order.

SOLUTION: 

  
import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueExample {

 public static void main(String args[]){
  PriorityQueue< String >pq=new PriorityQueue< String >(10,new CountryName());
  
  pq.add("India");
  pq.add("Bangla Desh");
  pq.add("USA");
  pq.add("Australia");
  pq.add("Israel");
  pq.add("United Kingdom");
  pq.add("Rasia");
  
  System.out.println("Country names in descending order: ");
  while( pq.size() > 0 ) {
   System.out.println(pq.poll());
  }
 }
}

class CountryName implements Comparator< String > {
 
 public int compare(String a, String b) {
  return b.compareToIgnoreCase(a);
 }
}

No comments:

Post a Comment