2012-11-23 39 views
10

我想修剪一個TreeMultimap,並且返回(但修剪)具有相同的結構TreeMultimap。例如,我有不同的新聞提供商返回無序的消息。我需要按日期對新聞進行排序,並在最近的日期按照排序後的multimap維護這種排序。然後我需要能夠返回最新的X新聞。按日期,可能有很多新聞。如何從Iterable/Collection創建TreeMultimap?

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

因爲沒有修剪,或者TreeMultimap的大小,我已經成功地返回Iterable並限制與成果,但如何建立從IterableTreeMultimap

從本質上講,這個想法是:

  • 創造新的分類TreeMultimap
  • 把儘可能多的條目有可用的(
  • 修剪X和返回地圖

而且,例如,如果我想實現類似功能的分頁,那麼不同的數據集怎麼樣?

以下是如何返回最近5條新聞,例如

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

但是,如何從結果中創建一個新的Multimap?

最簡單的方法是作爲迭代一樣簡單,創造一個新的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); 

我在想,如果有一個實際的實用工具類/構造函數,可以直接做到這一點。這種使用Iterables的方法是我能想到的唯一方法。也可能有其他方法。

+0

因此,您有'Iterable ',並且您想從中創建'TreeMultimap'?我無法在這裏找到'Iterables#limit' http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html它有什麼作用? –

+0

嗨,這是番石榴,不是谷歌收藏。 http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Iterables.html – Tony

+0

Ahh好的,'Iterables.limit'返回'Iterable',所以這個不會中斷,Map.Entry <日期,字符串> lastFiveNews = Iterables.limit(latestNews.entries(),5)'你不想要'Iterable '? –

回答