简体   繁体   English

Java:获取Guava Multimap给定键范围内的值计数

[英]java: get count of values within a given key range of Guava Multimap

I have a TreeMultimap<Integer, String> , which includes duplicate keys also. 我有一个TreeMultimap<Integer, String> ,它也包含重复的键。

I want to get the count of values which lies within a specific key range, that too with O(logN) time complexity. 我想获取位于特定键范围内的值计数 ,这也具有O(logN)时间复杂度。

I tried by first converting the TreeMultimap to a SortedMap by using its method asMap() and then creating a submap in the required range and fetching its size. 我首先尝试通过使用asMap()的方法asMap()TreeMultimap转换为SortedMap ,然后在所需范围内创建一个submap并获取其大小。

SortedMap<Integer, Collection<String>> sortedMap = mapList.getTmm().asMap();
return sortedMap.subMap(beg,end).size();

Is it having complexity O(logN) ? 它具有O(logN)的复杂度吗?

Also, I faced a problem here. 另外,我在这里遇到了一个问题。 When a TreeMultimap is converted to SortedMap , the values are objects of Collection class. TreeMultimap转换为SortedMap ,值是Collection类的对象。 ie The key-value pair having duplicate keys in TreeMultimap is included in a single Collection class. 即,在TreeMultimap具有重复键的键值对包含在单个Collection类中。 So the method size() returns wrong value. 因此,方法size()返回错误的值。

Is there any other way I an achieve this? 我还有其他方法可以实现这一目标吗? Any help is appreciated. 任何帮助表示赞赏。

You can try SortedMultiset , which has a method for ranged query: 您可以尝试SortedMultiset ,它具有用于范围查询的方法:

subMultiset : subMultiset

Returns a view of this multiset restricted to the range between lowerBound and upperBound. 返回此多集的视图,该视图限制在lowerBound和upperBound之间。

Sample code: 样例代码:

import com.google.common.collect.*;

public class GuavaMultiMap {
    public static void main(String [] args) {
        Multimap<Integer, String> map = TreeMultimap.create();
        map.put(0, "-1");
        map.put(1, "a");
        map.put(1, "b");
        map.put(2, "c");
        map.put(2, "d");
        map.put(3, "e");

        SortedMultiset<Integer> keys = TreeMultiset.create();
        keys.addAll(map.keys());

        SortedMultiset<Integer> range = keys.subMultiset(1, BoundType.CLOSED, 3, BoundType.OPEN);
        System.out.println(range.size());
    }
}

Output: 4 输出 4

The above code does not operate in O(log(N)) time because this line keys.addAll(...); 上面的代码无法在O(log(N))时间内运行,因为此行keys.addAll(...); is O(n) . O(n) However, if you keep a SortedMultiset updated together with the Multimap , you should be able to trade space for time. 但是,如果您将SortedMultisetMultimap一起更新,则应该可以交换空间。

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

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