Find The Closest Answer in HashMap

前端 未结 6 1125
谎友^
谎友^ 2020-12-16 13:07

I want to search for a key in a hashmap and find the nearest one to that key!

    HashMap map = new HashMap();
         


        
6条回答
  •  臣服心动
    2020-12-16 13:37

    You cannot do it with HashMap without iterating over all of its keys. I assume that this is not what you are after, so here is a way do it with a TreeMap:

    TreeMap map = new TreeMap();
    Long key = 42;
    Map.Entry low = map.floorEntry(key);
    Map.Entry high = map.ceilingEntry(key);
    Object res = null;
    if (low != null && high != null) {
        res = Math.abs(key-low.getKey()) < Math.abs(key-high.getKey())
        ?   low.getValue()
        :   high.getValue();
    } else if (low != null || high != null) {
        res = low != null ? low.getValue() : high.getValue();
    }
    

提交回复
热议问题