如何从 Java 中的哈希映射中获取所有最小值

New*_*ent 3 java hashmap

我有一个哈希映射,其中包含请求类型的键对象和整数类型的值。我使用以下代码迭代地图并获取所有最小值,然后将它们的键添加到列表中。我向 ALL 强调,因为键是唯一的,但值可以重复,因此可能存在多个具有最小值的映射元素。

然而,这段代码只给了我一个这样的元素,即它通过迭代找到的第一个元素,尽管我知道还有更多。例如,假设地图有以下请求 - 即键(我给出请求 ID): 3 | 5 | 2 其各自的值为: 8 | 4 | 4. 因此,在本例中,我们有两个最小元素,即共享最小值 ID 5 和 ID 2 的两个元素,两者的值均为 4。该代码将仅将 ID 为 5 的元素添加到我的列表中,即是,其中第一个。

我必须注意,有一个类似的线程(Hashtable 中的最大值的 Key),但提供的解决方案在我的情况下不起作用。

这是代码:

 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());

      }
Run Code Online (Sandbox Code Playgroud)

任何建议或解释为什么会发生这种情况,我们将不胜感激。

编辑:新方法

好吧,我找到了解决方案。它并不优雅,但很有效。这是代码。

    // 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());

       }

    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*eid 5

我建议您分两步进行

  1. 求最小值,存入min
  2. 查找所有值等于的元素min

这是一个代码示例:

// find minimum first
int min = Integer.MIN_VALUE;
for(Entry<Request, Integer> entry : this.map.entrySet()) {
    min = Math.min(min, map.getValue())
}

// add all elements that have a value equal to min
List<Request> minKeyList = new ArrayList<Request>();
for(Entry<Request, Integer> entry : this.map.entrySet()) {
    if(min.getValue() == min) {
        minKeyList.add(entry.getKey());
    }
}
Run Code Online (Sandbox Code Playgroud)