Java – how do I create a treemultimap from an Iterable / collection?

I'm pruning a tree Multimap and returning the same structured tree Multimap (but pruning) For example, I have different message providers that return unordered messages I need to sort messages by date and keep sorting in the sorted multi - graph according to the latest date Then I need to be able to return the latest x message By date, there may be a lot of news

TreeMultimap<Date,String> latestNews = TreeMultimap.create(Ordering.natural().reverse(),Ordering.natural());

Because there is no pruning or size for the treemultimap, I have tried to return an iteratable and limit the results, but how to create a new treemultimap from the iteratable?

Basically, the idea is:

>Create a new sort treemultimap > put as many entries as possible (available) > trim to X and return to the map

In addition, if I want to implement paging with similar functions, what about different data sets?

The following is an example of returning the last 5 messages

Map.Entry<Date,String> lastFiveNews = Iterables.limit(latestNews.entries(),5)

But how to create a new Multimap from the results?

The simplest method is as simple as iterating and creating a new treemultimap:

TreeMultimap<Date,String> lastFiveNews = TreeMultimap.create(Ordering.natural().reverse(),Ordering.natural());

for (Map.Entry<Date,String> dateStringEntry : Iterables.limit(latestNews.entries(),5)) {
    lastFiveNews.put(dateStringEntry.getKey(),dateStringEntry.getValue());
}
latestNews.clear();
latestNews.putAll(lastFiveNews);

I wonder if there is an actual class / constructor that can do this directly This method of using iterables is the only one I can think of There may be other ways

Solution

What you are already doing is exactly what you should do

You may be right https://code.google.com/p/guava-libraries/issues/detail?id=320 Is interested in the discussion, which is relevant (this actually seems to be a practical use case for these methods.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>