Partial search in HashMap

前端 未结 5 773
后悔当初
后悔当初 2020-11-29 03:55

I need to create phone book kind of thing. It contains name & number. Now when I type letters matching list should be returned. For the example given below, when I type

5条回答
  •  眼角桃花
    2020-11-29 04:47

    Use guava Multimap will ease your solution.

    The key is first letter of name, the value is a Collection containing all name-phone pair which name is started with the key(first letter).

    Example:

        public void test(){
          //firstLetter -> list of name-phone pair
          Multimap mMap =  ArrayListMultimap.create();
    
          put(mMap, "Brown",  "+1236389023");
          put(mMap, "Bob",    "+1236389023");
          put(mMap, "Harmer", "+1236389023");
          put(mMap, "Harris", "+1236389023");
          put(mMap, "Hawken", "+1236389023");
          put(mMap, "Hosler", "+1236389023");
    
          //Test
          System.out.println(mMap.get("H"));
       }
    
       void put(Multimap mMap, String name, String phone){
          mMap.put(name.substring(0,1), new Pair(name, phone));
       }
    
       public static class Pair{
          String name;
          String phone;
    
          public Pair(String name, String phone) {
             this.name = name;
             this.phone = phone;
          }
    
          @Override
          public String toString() {
             return "Pair [name="+name+", phone="+phone+"]";
          }
    

    }

提交回复
热议问题