简体   繁体   English

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

[英]TreeMap, how to get Key to obtain its information

I was wondering, how can I get the key in a TreeMap, to get that key's info? 我想知道如何在TreeMap中获取密钥,以获取该密钥的信息? For example, I've declared a TreeMap like this: 例如,我已经声明了一个TreeMap像这样:

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

DictionaryTerm is just a simple class which has just two variables, "String term" and " int number". DictionaryTerm只是一个简单的类,只有两个变量“ String term”和“ int number”。

TermComparator is a class to compare two keys: TermComparator是用于比较两个键的类:

class TermComparator implements Comparator<DictionaryTerm> {

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

} }

Let's assume the TreeMap has already an entry like this: ("LedZeppelin",55) --> 25 where (LedZeppelin,55) is the key and 25 its value. 假设TreeMap已经有一个这样的条目:(“ LedZeppelin”,55)-> 25其中(LedZeppelin,55)是键,其值25。

Now let's say I have this variable: 现在让我们说我有这个变量:

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

How can I find that "aTerm" in the TreeMap and obtain the key it to read its info? 如何在TreeMap中找到该“ aTerm”并获取其密钥以读取其信息? Considering that the TermComparator I created, compares by the String term. 考虑到我创建的TermComparator,按String项进行比较。

Thanks in advcance. 提前感谢。

I suppose you are interested in getting the key from TreeMap that compares as equal to aTerm , because getting the value would be easy ( miniDictionary.get(aTerm) ). 我想您有兴趣从TreeMap获取与aTerm相等的aTerm ,因为获取值很容易( miniDictionary.get(aTerm) )。

For getting the key, you can use floorKey() . 要获取密钥,可以使用floorKey() This method returns "the greatest key less than or equal to the given key, or null if there is no such key", so you have to check for null and equality first: 此方法返回“小于或等于给定键的最大键,如果没有这样的键,则返回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
    }

If you want to get both key and value, use floorEntry() . 如果要同时获取键和值,请使用floorEntry()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM