3

I have this code to take a map and sort it by key I then reverse the map to get them with the largest elements first.

Ordering<String> valueComparator = 
       Ordering.natural().onResultOf(Functions.forMap(WordMap))
                         .compound(Ordering.natural());

WordMapSorted = ImmutableSortedMap.copyOf(WordMap, 
                                  Collections.reverseOrder(valueComparator));

I'd like to know two things

  1. How can I get only the keys with a value above 10? I feel like given the sorting with guava there should be an easy way to specify a cutoff point (since once you reach a value below the threshold, you simply get all the items before it)

  2. How can I get the first 100 entries in the map (still in the form of a map). I know I can just get an array of keys and get the first 100, but I want the first 100 map entries. I know that normally a map has no order, but in this case it was sorted and made immutable so it does have order.

4

1 回答 1

4

第一个观察:没有必要使用Collections.reverseOrder(valueComparator),当你可以使用时valueComparator.reverse()

1 需要一些技巧:

int index = Collections.binarySearch(WordMapSorted.values().asList(), 11);
index = (index >= 0) ? index : -index - 1;
// the elements at and after index have value strictly greater than 10
return WordMapSorted.keySet().asList().subList(index, WordMapSorted.size());

2是可行的,像这样:

WordMapSorted.headMap(WordMapSorted.keySet().asList().get(100));
于 2013-07-03T20:57:35.263 回答