<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package tests;

import java.util.*;

/**
 * Shows how to use priority queues with custom comparators.
 *
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 15/11/12 11:13 AM
 */
public class PQ {
	static class Data {
		public int first;
		public int second;
	}

	public static void main(String[] args) {

		Comparator&lt;Data&gt; comparator = new Comparator&lt;Data&gt;(){
			@Override
			public int compare(final Data o1, final Data o2){
				// for smaller values having higher priority
				if ( o1.second &gt; o2.second ) return 1;
				else if ( o1.second &lt; o2.second ) return -1;
				return 0;
			}
		};

		Random generator = new Random();

		int initialCapacity = 10;
		PriorityQueue&lt;Data&gt; pq = new PriorityQueue&lt;Data&gt;(initialCapacity, comparator);

		for ( int a = 0; a &lt; 10; a++ ) {
			Data tmp = new Data();
			tmp.first = generator.nextInt() % 1000;
			tmp.second = generator.nextInt() % 1000;
			pq.add(tmp);
		}

		System.out.println("all data:");
		Iterator&lt;Data&gt; iter = pq.iterator();
		while (iter.hasNext()) {
			Data tmp = iter.next();
			System.out.println(tmp.first + " " + tmp.second);
		}

		Data best = pq.peek();
		System.out.println("the best element: (" + best.first + ", " + best.second + ")");

		System.out.println("prioritised data:");
		Data tmp = pq.poll();
		while ( tmp != null ) {
			System.out.println(tmp.first + " " + tmp.second);
			tmp = pq.poll();
		}

	}
}
</pre></body></html>