Tony
Tony

Reputation: 103

How to create a TreeMultimap from an Iterable/Collection?

I'm trying to trim a TreeMultimap, and have the same structured TreeMultimap returned (but trimmed). For example, i have different news providers that returns unordered news. I need to sort the news by date and maintain this sort in the sorted multimap by most recent date. Then i need the ability to return the most recent X news. Per date, there may be many news.

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

Because there is no trim, or size of the TreeMultimap, I've managed to return an Iterable and limit the results with that, but how to create a new TreeMultimap from the Iterable?

Essentially, the idea is:

Also, what about different sets of data for example if I want to implement paging like features?

Here is how to return the last 5 news for example

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

But how do I create a new Multimap from the result?

Easiest way would be 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 was wondering if there is an actual utility class/constructor that can do that directly. This approach using the Iterables was the only one I could think of. There may be other approaches too.

Upvotes: 10

Views: 6023

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

The way you're already doing it is exactly what you should do.

You may be interested in the discussion on https://code.google.com/p/guava-libraries/issues/detail?id=320, which is related. (This seems like an actual valid use case for those methods, actually.)

Upvotes: 3

Related Questions