値の属性に基づいてJavaTreeMapをソートしたいと思います。具体的にはTreeMap<Integer, Hashset<Integer>>
、のサイズに基づいて並べ替えたいと思いますHashset<Integer>
。これを達成するために、私は次のことを行いました。
コンパレータクラス:
private static class ValueComparer implements Comparator<Integer> {
private Map<Integer, HashSet<Integer>> map = null;
public ValueComparer (Map<Integer, HashSet<Integer>> map){
super();
this.map = map;
}
@Override
public int compare(Integer o1, Integer o2) {
HashSet<Integer> h1 = map.get(o1);
HashSet<Integer> h2 = map.get(o2);
int compare = h2.size().compareTo(h1.size());
if (compare == 0 && o1!=o2){
return -1;
}
else {
return compare;
}
}
}
使用例:
TreeMap<Integer, HashSet<Integer>> originalMap = new TreeMap<Integer, HashSet<Integer>>();
//load keys and values into map
ValueComparer comp = new ValueComparer(originalMap);
TreeMap<Integer, HashSet<Integer>> sortedMap = new TreeMap<Integer, HashSet<Integer>>(comp);
sortedMap.putAll(originalMap);
問題:
originalMap
同じサイズの値が3つ以上含まれている場合、これは機能しません。その他の場合は、問題なく動作します。マップ内の3つ以上の値が同じサイズの場合、新しいソート済みマップの3番目の値はnullであり、アクセスしようとするとNullPointerExceptionがスローされます。
何が問題なのかわかりません。誰かが指摘できれば、Wouleはいいですね。
更新: 2つの値が同じサイズの場合に機能する例を次に示します。http://ideone.com/iFD9c 上記の例では、52〜54行目のコメントを外すと、このコードは失敗します。これが私の問題です。