我想从哈希表中找到所有"具有最大值的条目对",我的哈希表是这样的 -
Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
ht.put(1, 4);
ht.put(2, 2);
ht.put(3, 4);
ht.put(4, 2);
ht.put(5, 4);
我想找到这些键值对:<1,4>, <3,4>, <5,4>
,我知道可以通过首先找到最大值条目来完成,然后通过哈希表重申以查找其他类似的条目。但我想知道是否有任何优雅/更简单的方法可以做到这一点。
知道吗?
int max = Integer.MIN_VALUE;
final List< Entry< Integer, Integer > > maxList =
new ArrayList< Entry< Integer, Integer > >();
for ( final Entry< Integer, Integer > entry : ht.entrySet() ) {
if ( max < entry.getValue() ) {
max = entry.getValue();
maxList.clear();
}
if ( max == entry.getValue() )
maxList.add( entry );
}
您可以使用 Eclipse Collections 中的一些迭代模式来实现此目的。
MutableMap<Integer, Integer> map = UnifiedMap.newWithKeysValues(1, 4)
.withKeyValue(2, 2)
.withKeyValue(3, 4)
.withKeyValue(4, 2)
.withKeyValue(5, 4);
Integer maxValue = map.valuesView().max();
RichIterable<Pair<Integer,Integer>> pairs =
map.keyValuesView().select(
Predicates.attributeEqual(Functions.<Integer>secondOfPair(), maxValue));
Assert.assertEquals(
HashBag.newBagWith(Tuples.pair(1, 4), Tuples.pair(3, 4), Tuples.pair(5, 4)),
pairs.toBag());
如果您只需要每对钥匙,则可以收集它们。
RichIterable<Integer> maxKeys = pairs.collect(Functions.<Integer>firstOfPair());
注意:我是 Eclipse Collections 的提交者。
List<Integer> keysForMaximums = new ArrayList<Integer>();
int currentMax = Integer.MIN_VALUE;
while(iterator.hasNext()) {
int key = /*get key from iterator*/;
int val = /*get value from iterator*/;
if(val > currentMax) {
currentMax = val;
keysForMaximums.clear();
}
if(val == currentMax)
keysForMaximums.add(key);
}
然后 keysForMax 将是包含映射中找到的最大值的键列表
这样做它会创建一个空的整数列表,以及一个表示找到的最大数量的数字(默认为最低 int 值),然后它遍历地图并检查这家伙是否有更大的最大值,清除列表并将他设置为最大最大值,然后如果他是最大最大值,请添加他的键
据我所知,现在不使用哈希表。
我会使用HashMap(它也是一个KeyValue-List)。
您可以使用
for (Entry<Integer, Integer> entry : myMap.entrySet()) {
// Your stuff here
}
使用此方法,您可以获取值和键。
有关更多信息,请参阅 Java 文档。
此致敬意
您可以按值排序,然后向后搜索,直到找到 != 最后一个值。
但我也喜欢你的方法。它具有线性复杂性,即对于大多数用例来说还可以。