優先度付きキューメモ
Javaで優先度付きキューを取り扱うときに毎回調べている気がする。メモする。 - PriorityQueue (Java Platform SE 8 )
Queue<Integer> que = new PriorityQueue<>(); que.add(3); que.add(1); que.add(4); que.add(1); que.add(5); while(!que.isEmpty()){ int i = que.poll(); System.out.print(i+" "); } // 実行結果 // 1 1 4 3 5
自然順序でソートされる。 数値だったら小さい順。
大きい順とか、自然順序以外のソートをしたい場合はComparator
を引数に渡す。
Queue<Integer> que = new PriorityQueue<>((a,b)->Integer.compare(b,a)); que.add(3); que.add(1); que.add(4); que.add(1); que.add(5); while(!que.isEmpty()){ int i = que.poll(); System.out.print(i+" "); } // 実行結果 // 5 4 3 1 1
java.util.Collections#reverseOrder()
を使用する方法もあるけど、ラムダ式で書くほうが拡張性高くて好き(二次元配列でソートするときとか)