キーが変数であるキーに基づいてツリー マップを並べ替えたいので、並べ替えは変数値に基づいて行う必要があります。どうすればこれを達成できますか? コードを介して実装する組み込みの並べ替えメソッドで使用したいのですが、例を含む返信は非常に役立ちます。
3 に答える
TreeMap
(これは を実装していますSortedMap
)キーを正しい順序で自動的に保存します:
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "one");
map.put(3, "three");
map.put(2, "two");
// prints one two three
for(Integer key : map.keySet()) {
System.out.println(map.get(key));
}
Key-Type (その場合はInteger
) を実装する任意のクラスを使用できますComparable
(または をComparator
作成するときに を提供できますTreeMap
) 。
編集:さて、これはマップを再マップする方法の提案です。
Map<Integer, String> oldMap; // get oldMap from somewhere
// Prepare remapping
Map<Integer, String> newMap = new TreeMap<Integer, String>();
Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
// Store a new key for each old key
keyMap.put(oldKey, newKey);
// fill the newMap
for(Integer oldKey : keyMap.keySet()) {
newMap.put(keyMap.get(oldKey), oldMap.get(oldKey));
}
oldMap = newMap; // if needed
ツリーマップは、バランスのとれた二分探索木である赤黒木です。言い換えれば、ツリー操作が O(lg n) の複雑さを持つように、ツリーは高さのバランスが取れた状態で既にソートされています (または、二分探索ツリーの規則に従って配置されています)。しかし、あなたが望むのは、すべてのキーをソートされた順序で出力することだと思います。これは、ツリーマップでインオーダー トラバーサルを実装するのと同じくらい簡単です。または、keySet() メソッドを使用して Set を取得し、値を反復処理することもできます。
例: 順序通りのトラバーサル
void inorderTraversal( Node root ){
if( root == null ) return;
inorderTraversal( root.getLeft() );
root.printValue();
inorderTraversal( root.getRight() );
}
編集:
わかりました、これはあなたが望むものだと確信しています。値でソートしたい:
Map<String, Integer> map = new TreeMap<String, Integer>();
map.put("one", 8);
map.put("two", 10);
map.put("three", 9);
map.put("hundred", 1);
System.out.println(map.values());
出力:
[1, 8, 9, 10]
したがって、これは文字列値のソートでも機能します。
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(8, "one");
map.put(10, "two");
map.put(9, "three");
map.put(1, "hundred");
System.out.println(map.values());
出力:
[hundred, one, three, two]
また、「変数キー」と変数値を持つことはまったく別のものであることに注意してください。
TreeMap
インターフェイスを実装し、SortedMap
何もしなくてもそのキーでソートされます。
マップは、使用されるコンストラクターに応じて、キーの自然順序付けに従って、または
Comparator
マップ作成時に指定された によってソートされます。