您可以使用 TreeMap 和 Entry 像这样使用常规 Java 来做到这一点。
如果提供的参数不存在范围,则返回 Not Found
这是包含范围的地图。
- 这是一个树形图
- 键是范围的下半部分。
- 值为
AbstractMap.SimpleEntry,包含范围的上半部分和字符串。
NavigableMap<Integer, AbstractMap.SimpleEntry<Integer,String>> nmap =
new TreeMap<>();
构建地图的方法。
public static void build(
NavigableMap<Integer, AbstractMap.SimpleEntry<Integer, String>> map,
int start, int end, String v) {
AbstractMap.SimpleEntry<Integer, String> e = new
AbstractMap.SimpleEntry<Integer,String>(end,v);
map.put(start, e);
}
用于检索字符串的 lambda。
Function<Integer,String> get = k->{
Entry<Integer, AbstractMap.SimpleEntry<Integer,String>> entry =
nmap.floorEntry(k);
if (entry == null) {
return "Not Found";
}
if (k > entry.getValue().getKey()) {
return "Not Found";
}
return entry.getValue().getValue();
};
为每个范围构建地图
build(nmap, 10, 75, "A");
build(nmap, 95, 200, "A");
build(nmap, 300, 455, "B");
build(nmap, 570, 650, "C");
build(nmap, 201, 250, "A");
build(nmap, 255, 275, "B");
测试
int[] testData = { 9, 23, 255, 99, 94, 201 };
for (int i : testData) {
System.out.printf("%4d -> %s%n",i, get.apply(i));
}
打印
9 -> Not Found
23 -> A
255 -> B
99 -> A
94 -> Not Found
201 -> A