Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a TreeMultimap from an Iterable/Collection?

Tags:

java

guava

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:

  • create new sorted TreeMultimap
  • put as many entries as there are available (
  • trim to X and return the map

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.

like image 985
Tony Avatar asked Nov 23 '12 10:11

Tony


1 Answers

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.)

like image 184
Louis Wasserman Avatar answered Sep 20 '22 05:09

Louis Wasserman