我有一个Hash Map,其中包含Request类型的Keys对象和Integer类型的值.我使用以下代码迭代地图并获取所有最小值,然后将其键添加到列表中.我强调所有因为键是唯一的但值可以是重复的,因此可能有多个具有最小值的地图元素.
但是,这段代码只给了我一个这样的元素,即它通过迭代找到的第一个元素,即使我知道还有更多元素.例如,让我们说地图有以下请求 – 即密钥(我给出请求ID):3 | 5 | 2和它们各自的值是:8 | 4 |因此,在这个例子中,我们有两个最小元素,即两个共享最小值的元素,ID 5和ID 2,两者都是值4.代码将只向我的列表中添加ID为5的元素,即是,他们中的第一个.
我必须注意,有一个类似的线程(Key for maximum value in Hashtable),但提供的解决方案在我的情况下不起作用.
这是代码:
Entry min = null;
List minKeyList = new ArrayList();
for(Entry entry : this.map.entrySet()) {
if (min == null || min.getValue() > map.getValue()) {
min = entry;
minKeyList.add(entry.getKey());
}
任何建议或解释为什么会发生这种情况将不胜感激.
编辑:新方法
好吧,我找到了解决方案.它不优雅,但它的工作原理.这是代码.
// list for finding the min value
List minValList = new ArrayList();
// List for keeping the keys of the elements with the min value
List minKeyList = new ArrayList();
// scan the map and put the values to the value list
for(Entry entry : this.map.entrySet()) {
minValList.add(entry.getValue());
}
// scan the map
for(Entry 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());
}
}
解决方法:
我建议你分两步:
>找到最小值,以分钟为单位存储
>查找值等于min的所有元素
这是一个代码示例:
// find minimum first
int min = Integer.MIN_VALUE;
for(Entry entry : this.map.entrySet()) {
min = Math.min(min, map.getValue())
}
// add all elements that have a value equal to min
List minKeyList = new ArrayList();
for(Entry entry : this.map.entrySet()) {
if(min.getValue() == min) {
minKeyList.add(entry.getKey());
}
}
标签:java,hashmap
来源: https://codeday.me/bug/20190825/1722451.html