【问题标题】:TreeMap, how to get Key to obtain its informationTreeMap,如何获取Key获取其信息
【发布时间】:2016-05-15 22:26:53
【问题描述】:

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

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

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

TermComparator 是一个比较两个键的类:

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,按字符串项进行比较。

提前感谢。

【问题讨论】:

    标签: java dictionary treemap


    【解决方案1】:

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

    要获取密钥,您可以使用floorKey()。此方法返回“小于或等于给定键的最大键,如果没有这样的键,则返回 null”,因此您必须先检查 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()

    【讨论】:

    • 非常感谢,尽管我没有清楚地解释自己,但您已经成功并给出了一个很好的答案。谢谢。只是一件事,什么是 dictionaryTerm ?在 System.out.println();应该是 floorKey 吗?
    • 是的,对不起,应该是 floorKey
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多