0

可能重复:
不确定我是否应该搜索或排序我的哈希图

嗨,我有一个年龄列表,我需要找到 30 岁以上的人,有没有可能在 hashmap 中搜索?(请注意,我可能还需要寻找其他年龄段的人,所以为了代码的简单性,我不想使用两个不同的列表)

简而言之:我的目标是找到一种在 HashMap 中搜索具有特定值的元素的方法

样品清单是

element1 40
element2 4
element3 66
element4 5

我想找到值大于 40 和值大于或等于 66 的那些。

除了遍历所有值之外,还有其他方法吗?

4

3 回答 3

2

AHashMap仅提供按键搜索,因此您必须迭代整个集合并过滤您不想要的元素。

您可以使用 for each 循环来做到这一点:

for (Entry<MyKey,MyValue> e : map.entrySet()) { 
    if (e.getValue() >= 40) { ....} //e.getKey() is an element with the needed value
    if (e.getValue() >= 66) { ... }
}

另一种方法是持有 a NavigableMap,将值映射到与它们相关的元素并使用NavigableMap.subMap()(请注意,如果您可能有重复值,则值NavigableMap应该是 a List

于 2012-10-03T12:42:43.747 回答
1

使用番石榴,您可以执行以下操作

import com.google.common.base.Predicate;
import com.google.common.collect.Maps;

public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("element1", 40);
        map.put("element2", 4);
        map.put("element3", 66);
        map.put("element4", 5);
        Map<String, Integer> filteredMap = Maps.filterValues(map,
                Predicates.equalTo(66));
    }

由于您所需的年龄可能会改变,您可以拥有一个用于过滤的 AgePredicate

class AgePredicate implements Predicate<Integer> {
    int minAge;

    public AgePredicate(int minAge) {
        super();
        this.minAge = minAge;
    }

    @Override
    public boolean apply(Integer age) {
        return age > minAge;
    }
}

并在您的过滤器中使用它,如下所示

Map<String, Integer> filteredMap = Maps.filterValues(map,new AgePredicate(66));
于 2012-10-03T12:55:26.100 回答
0

您可以像这样遍历键值:

   Iterator<String> it = hm.keySet().iterator();
    while (it.hasNext()){
        String key = it.next();
        if (hm.get(key) >= 40) {
            // do some stuff...
        }
    }
于 2012-10-03T12:44:18.720 回答