title: How to create a TreeMultimap from an Iterable/Collection?
body: <p>I'm trying to trim a <code>TreeMultimap</code>, and have the same structured <code>TreeMultimap</code> 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.</p>
  
  <pre><code>TreeMultimap&lt;Date, String&gt; latestNews = TreeMultimap.create(Ordering.natural().reverse(), Ordering.natural());
  </code></pre>
  
  <p>Because there is no trim, or size of the <code>TreeMultimap</code>, I've managed to return an <code>Iterable</code> and limit the results with that, but how to create a new <code>TreeMultimap</code> from the <code>Iterable</code>?</p>
  
  <p>Essentially, the idea is:</p>
  
  <ul>
  <li>create new sorted TreeMultimap</li>
  <li>put as many entries as there are available (</li>
  <li>trim to X and return the map </li>
  </ul>
  
  <p>Also, what about different sets of data for example if I want to implement paging like features?</p>
  
  <p>Here is how to return the last 5 news for example</p>
  
  <pre><code>Map.Entry&lt;Date, String&gt; lastFiveNews = Iterables.limit(latestNews.entries(), 5)
  </code></pre>
  
  <p>But how do I create a new Multimap from the result?</p>
  
  <p>Easiest way would be as simple as iterating and creating a new <code>TreeMultimap</code>:</p>
  
  <pre><code>TreeMultimap&lt;Date, String&gt; lastFiveNews = TreeMultimap.create(Ordering.natural().reverse(), Ordering.natural());
  
  for (Map.Entry&lt;Date, String&gt; dateStringEntry : Iterables.limit(latestNews.entries(), 5)) {
      lastFiveNews.put(dateStringEntry.getKey(), dateStringEntry.getValue());
  }
  latestNews.clear();
  latestNews.putAll(lastFiveNews);
  </code></pre>
  
  <p>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.</p>