あなたのコードは最高です。ただし、データ構造の全体的な設計にはオーバーホールが必要なようです。 を使用SortedMap<?, SortedMap<?, ?>
していますが、親マップのキーは使用されていません。
ネストされた要素を持つツリーをそれで表現したいですか?あなたの仕事はツリーを平らにすることですか? その場合は、アプローチをサポートする Tree クラスを作成するか、インテリジェントな方法を使用してキーをマージします。
public class NestedKey implements Comparable<NestedKey> {
private Comparable[] entries;
public NestedKey(Comparable... entries) {
assert entries != null;
this.entries = entries;
}
public int compareTo(NestedKey other) {
for(int i = 0; i < other.entries.length; i++) {
if (i == entries.length)
return -1; // other is longer then self <=> self is smaller than other
int cmp = entries[i].compareTo(other.entries[i]);
if (cmp != 0)
return cmp;
}
if (entries.length > other.entries.length)
return 1; // self is longer than others <=> self is larger than other
else
return 0;
}
}
NestedKey
SortedMap のキーとして使用されるエントリは、各エントリを比較することによって他のオブジェクトNestedKey
と比較されます。存在するすべての要素にあるが、より多くのエントリを持つ NestedKeys は、より大きいと見なされます。したがって、次のような関係があります。
- NestedKey(1, 2, 3) < NestedKey(1, 2, 4)
- NestedKey(1, 3, 3) < NestedKey(2, 1, 1)
- NestedKey(1, 2, 3) < NestedKey(2)
NestedKey をキーとして使用する SortedMap を 1 つだけ使用すると、その.values()
セットは自動的にすべてのエントリを平坦化して返します。ただし、SortedMap の一部のみを使用する場合は、.subMap
. たとえば、すべてのエントリで 2 と 3 の間の NestedKeys を使用する場合は、次を使用します。.subMap(new NestedKey(2), new NestedKey(3))