我想你有兴趣从
TreeMap
相当于
aTerm
,因为获得价值很容易(
miniDictionary.get(aTerm)
).
要获取密钥,可以使用
floorKey()
。此方法返回“小于或等于给定键的最大键,如果没有该键,则返回null”,因此必须首先检查null和equality:
TermComparator termComparator = new TermComparator();
TreeMap<DictionaryTerm, Integer> miniDictionary = new TreeMap<>(termComparator);
miniDictionary.put(new DictionaryTerm("LedZeppelin", 55), 25);
DictionaryTerm aTerm = new DictionaryTerm("LedZeppelin",100);
DictionaryTerm floorKey = miniDictionary.floorKey(aTerm);
if (floorKey != null && termComparator.compare(aTerm, floorKey) == 0) {
System.out.println(floorKey.getNumber()); // prints 55
}
如果要同时获取键和值,请使用
floorEntry()
.