Find The Closest Answer in HashMap

前端 未结 6 1128
谎友^
谎友^ 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:34

    Using a NavigableMap like a TreeMap

    long key = 
    NavigableMap map = new TreeMap();
    
    Long before = map.floorKey(key);
    Long after = map.ceilingKey(key);
    if (before == null) return after;
    if (after == null) return before;
    return (key - before < after - key 
           || after - key < 0) 
           && key - before > 0 ? before : after;
    

提交回复
热议问题