Java:如何从Hashtable中查找所有“具有最大值的条目对”

时间:2012-10-01 20:47:09

标签: java hashtable max

我想从Hashtable中找到所有“具有最大值的条目对”,我的Hashtable就是这样 -

    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>,我知道可以先找到最大值条目,然后通过Hashtable重复查找其他类似条目。但我想知道是否有任何优雅/简单的方法来做到这一点。

任何想法?

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

您可以使用GS 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());

注意:我是GS Collections的开发人员。

答案 2 :(得分:1)

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

然后keysForMaximum将是包含在地图中找到的最大值的键列表

这样做会产生一个空的整数列表,以及一个代表找到的最大数量的数字(默认为最低的int值),然后它会通过地图并检查这些人是否有更大的最大值,清除列表并把他设置为最大的最大值,然后如果他是最大的最大值加上他的钥匙

答案 3 :(得分:1)

据我所知,这些天没有使用哈希表 我会使用HashMap(它也是KeyValue-List)。

您可以使用
来迭代完整的地图

for (Entry<Integer, Integer> entry : myMap.entrySet()) {  
    //  Your stuff here  
}

使用此方法,您将获得值和键 有关详细信息,请参阅Java Doc

祝你好运

答案 4 :(得分:0)

你可以按值排序,然后向后搜索,直到你得到一个值!=最后一个值。

但我也喜欢你的做法。它具有线性复杂性,即大多数用例都可以。