Request タイプの Keys オブジェクトと Integer タイプの Values を持つ Hash Map があります。次のコードを使用して、マップを反復処理し、すべての最小値を取得してから、それらのキーをリストに追加します。キーは一意ですが、値は重複する可能性があるため、すべてを強調します。したがって、最小値を持つ複数のマップ要素が存在する可能性があります。
ただし、このコードでは、そのような要素は 1 つしか得られません。つまり、反復によって最初に見つかった要素です。他にもあることがわかっているにもかかわらずです。たとえば、マップに次のリクエストがあるとします。つまり、キーです (リクエスト ID を指定します)。5 | 2 で、それぞれの値は次のとおりです。4 | 4. したがって、この例では 2 つの最小要素があります。つまり、最小値 ID 5 と ID 2 を共有する 2 つの要素で、どちらも値 4 です。コードは、ID 5 の要素のみをリストに追加します。それらの最初のものです。
同様のスレッド ( Key for maximum value in Hashtable ) があることに注意する必要がありますが、提供されたソリューションは私の場合は機能しません。
コードは次のとおりです。
Entry<Request, Integer> min = null;
List<Request> minKeyList = new ArrayList<Request>();
for(Entry<Request, Integer> entry : this.map.entrySet()) {
if (min == null || min.getValue() > map.getValue()) {
min = entry;
minKeyList.add(entry.getKey());
}
なぜこれが起こっているのかについての提案や説明をいただければ幸いです。
編集: 新しいアプローチ
さて、私は解決策を見つけました。エレガントではありませんが、機能します。これがコードです。
// list for finding the min value
List<Integer> minValList = new ArrayList<Integer>();
// List for keeping the keys of the elements with the min value
List<Request> minKeyList = new ArrayList<Request>();
// scan the map and put the values to the value list
for(Entry<Request, Integer> entry : this.map.entrySet()) {
minValList.add(entry.getValue());
}
// scan the map
for(Entry<Request, Integer> entry: this.map.entrySet()) {
// find the min value
if(entry.getValue() == Collections.min(minValList)) {
// add the keys of the elements with the min value at the keyList
minKeyList.add(entry.getKey());
}
}