not sure if I should search or sort my hashmap

后端 未结 6 1606
北恋
北恋 2021-01-23 16:28

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

6条回答
  •  一生所求
    2021-01-23 17:07

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

提交回复
热议问题