Question: > 
> **Possible Duplicate:**  
> 
> [not sure if I should search or sort my hashmap](https://stackoverflow.com/questions/12707769/not-sure-if-i-should-search-or-sort-my-hashmap) 
> 
> 
> 

Hi I have a list of people with their ages, I need to find those who are more than 30 years old, 
is there any possibility to search in a hashmap ? (please note that I may need to look for those in other age ranges as well so I prefer not to use two different lists for the sake of simplicity of code)

In short: My goal is to find a way to search for elements with specific values in HashMap

Sample list is 

```
element1 40
element2 4
element3 66
element4 5

```

I want to find those with values more than 40 and those with values more than or equal to 66.

Is there any other way than iterating through all values?

Answer: 
A `HashMap` provides a search by key only, so you will have to iterate the entire collection and filter the elements you don't want.

You can do it with a for each loop:

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

```

An alternative is holding a [`NavigableMap`](http://docs.oracle.com/javase/6/docs/api/java/util/NavigableMap.html) that maps from values to the elements that are relevant to them and use [`NavigableMap.subMap()`](http://docs.oracle.com/javase/6/docs/api/java/util/NavigableMap.html#subMap%28K,%20K%29) (note if you might have dupe values, the value of the `NavigableMap` should be a `List`)
With Guava you could do the following

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

```

Since your required age may change you could have an AgePredicate that is used for the filtering

```
class AgePredicate implements Predicate<Integer> {
    int minAge;

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

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

```

and use it in your filter as follows

```
Map<String, Integer> filteredMap = Maps.filterValues(map,new AgePredicate(66));

```