TreeMap,如何获取Key获取其信息

TreeMap, how to get Key to obtain its information

我想知道,如何在 TreeMap 中获取密钥,以获取该密钥的信息?例如,我声明了一个像这样的 TreeMap:

TreeMap miniDictionary = new TreeMap<DictionaryTerm,Integer>(new TermComparator());

DictionaryTerm 只是一个简单的 class,它只有两个变量,"String term" 和“int number”。

TermComparator 是一个 class 来比较两个键:

class TermComparator implements Comparator<DictionaryTerm> {

@Override
public int compare(DictionaryTerm e1, DictionaryTerm e2) {
    return e1.getTerm().compareTo(e2.getTerm());
}

}

让我们假设 TreeMap 已经有一个这样的条目:("LedZeppelin",55) --> 25 其中 (LedZeppelin,55) 是键,25 是它的值。

现在假设我有这个变量:

DictionaryTerm  aTerm = new DictionaryTerm("LedZeppelin",100);

如何在 TreeMap 中找到 "aTerm" 并获取它的密钥以读取其信息?考虑到我创建的 TermComparator 按字符串项进行比较。

提前致谢。

我想您有兴趣从 TreeMap 获取与 aTerm 比较相等的密钥,因为获取值很容易 (miniDictionary.get(aTerm))。

要获取密钥,您可以使用floorKey()。这个方法returns"the greatest key less than or equal to the given key, or null if there is no such key",所以要先检查是否为null和是否相等:

    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()