Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement tire map in java?

I want a tire map like blow:

Map<String,Object> map = new TireMap();
map.put("com","1");
map.put("com.aa","2");
map.put("com.aa.bb","3");

map.get("com");// return ["1","2","3"]
map.get("com.a"); //return ["2","3"]
map.get("com.aa"); //return ["2","3"]
// the key maybe full key or just key prefix

How to implement a map like this? Or is there already exits a map in Java API or open source?

It's very like innodb in mysql.

PS: Performance is very important. The storage items will be more than 1000W.

like image 969
lichengwu Avatar asked May 13 '13 05:05

lichengwu


1 Answers

I would try out TreeMap from java.util. This is a map which does what u need. It manages the keys based on a natural order (defined by a comparator in the key class). The methods tailMap and headMap gives you a map with keys you need.

Example

public static void main(String[] args) {
    TreeMap<String, Object> map = new TreeMap<String, Object>();

    map.put("com","1");
    map.put("com.aa","2");
    map.put("com.aa.bb","3");

    System.out.println(map.get("com"));
    System.out.println(map.tailMap("com").values()); // ["1","2","3"]

    System.out.println(map.get("com.aa")); //return ["2","3"]
    System.out.println(map.tailMap("com.aa").values());
}
like image 129
Pentarius Avatar answered Sep 26 '22 03:09

Pentarius