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
I'd suggest you to use NavigableMap (Implemented as TreeSet).
This implementation is a quite fast - O(log(N)), versus O(N) if you implement index based on lists.
Edit. Example:
class PersonsAgeIndex {
private NavigableMap> ageToPersons =
new TreeMap>();
public void addPerson( Person p ) {
List personsWithSameAge = this.ageToPersons.get( p.age );
if ( personsWithSameAge == null ) {
personsWithSameAge = new LinkedList();
this.ageToPersons.put( p.age, personsWithSameAge );
}
personsWithSameAge.add( p );
}
public List personsWithAgeLessThan( int age ) {
List persons = new LinkedList();
// persons with less age
for (List tmp : this.ageToPersons.headMap( age ).values()) {
persons.addAll( tmp );
}
return persons;
}
public List personsWithAgeInInterval( int minAge, int maxAge ) {
List persons = new LinkedList();
// persons with age, which: (minAge <= age <= maxAge)
for (List tmp : this.ageToPersons.subMap( minAge, true, maxAge, true ).values()) {
persons.addAll( tmp );
}
return persons;
}
}
class Person {
public final int age;
public Person(int age) {
this.age = age;
}
}