java - Binary Search Map which hashes values -


the following code provides simple version of class tracks how string inputed (method addpv) , can output k strings highest count in order (method firstk).

in simplified code below, binary seach tree (treeset) used track counts , keep order. secondary data structure (hashmap) used rapidly access elements in treeset. composite entry class containing string name , count used, count determines natural order , name hashcode.

the elegant way use bst (e.g. treemap) entry have count key , string name value. internal hashmap used efficiently access entries in bst in constant time. there standard data structure in common libraries general objects?

import java.util.*;  public class mostvisitedpages {     private hashmap<string,countentry> hm = new hashmap<>();     private treeset<countentry> ts = new treeset<>();      private static class countentry implements comparable<countentry>{         string page;         int count;          countentry (string page, int count){             this.page = page;             this.count = count;         }          @override         public int compareto(countentry entry){             int res = integer.compare(count,entry.count);             return res != 0 ? res: page.compareto(entry.page);         }          @override         public boolean equals(object obj){             if(this == obj) return true;             else if (obj==null || !(obj instanceof countentry)) return false;             else {return page.equals(((countentry)obj).page);}         }          @override         public int hashcode(){             return page.hashcode();         }     }      public void addpv(string p){         if(hm.containskey(p)){             countentry ce = hm.get(p);             ts.remove(ce);             ce.count += 1;             ts.add(ce);         } else {             countentry ce = new countentry(p,1);             ts.add(ce);             hm.put(p, ce);         }     }      public list<string> firstk(int k){         list<string> ret = new arraylist<>(k);          iterator<countentry> = ts.descendingiterator();         for(int = 0; i<k && i<hm.size(); i++){             ret.add(it.next().page);         }          return ret;     }    } 

yes, there treemap class in jdk.

it should fit needs.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -