重複の可能性:
Javaの値でMap <Key、Value>をソートする方法は?
私は次のようなHashMapを持っています:
Key Value
A 5
B 3
C 10
D 4
E 1
F 11
私は最も価値のあるものを見つける必要があります、あなたは私に何をするように提案しますか?それらを並べ替えて最初のものを取得する必要がありますか、それとも他のより速い方法がありますか?
重複の可能性:
Javaの値でMap <Key、Value>をソートする方法は?
私は次のようなHashMapを持っています:
Key Value
A 5
B 3
C 10
D 4
E 1
F 11
私は最も価値のあるものを見つける必要があります、あなたは私に何をするように提案しますか?それらを並べ替えて最初のものを取得する必要がありますか、それとも他のより速い方法がありますか?
検索要件の並べ替えを行うことはお勧めしません。@David Lamのアドバイスに従って、以下のように検索(反復)を実行して、最も価値の高いキーを見つけることができます。
Set<String> keys = myMap.keySet();
Iterator<String> keyIter = keys.iterator();
String highestValueKey = null;
while(keyIter.hasNext()){
String key = keyIter.next();
if(highestValueKey == null){
highestValueKey = key;
}else if(myMap.get(key).intValue() > myMap.get(highestValueKey).intValue()){
highestValueKey = key;
}
}
最後に、highestValueKey
最も高い値の要素のキーへの参照があります。
これは、aを使用し、値SortedMap
にaを渡すことで、はるかに簡単に解決できます。Comparator
final Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 5);
map.put("B", 3);
map.put("C", 10);
map.put("D", 4);
map.put("E", 1);
map.put("F", 11);
map.put("G", 11);
map.put("H", 10);
TreeMap<String, Integer> sorted = new TreeMap<String, Integer>(new Comparator<String>() {
// Note: this comparator imposes orderings that are inconsistent with equals.
@Override
public int compare(String a, String b) {
if (map.get(a) >= map.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
});
sorted.putAll(map);
Entry<String, Integer> first = sorted.firstEntry();
System.out.println("Highest value: " + first.getValue() + is for key: " + first.getKey());
// If duplicate keys are never a concern, you can stop here. Otherwise, one may
// continue below to find all keys that may be mapped to an equal highest value:
List<String> others = new LinkedList<String>();
for (Entry<String, Integer> entries : sorted.entrySet()) {
if (entries.getValue().equals(first.getValue())) {
others.add(entries.getKey());
} else {
break;
}
}
System.out.println("All keys mapped to this highest value: " + others);
プリントアウト:
Highest value: 11 is for key: G
All keys mapped to this highest value: [G, F]
キーを繰り返し処理し、最も高いキーを追跡しますO(n)
「最大値の検索」操作を頻繁に実行する必要がある場合は、TreeMapを使用することをお勧めします。
それ以外の場合、HashMapに値を挿入し、それを完全に制御できる場合は、 HashMapに値を挿入するときに、最大値を追跡します。
編集:ここに示すように、どちらの方法でもHashMapを使用する必要があります
または、バブルソートを使用して最高値を見つけることができます