title: What's the best way to get top N elements in a Map<String, Double> based on their values?
body: <p>For example, if I have a map consists of <code>{"A", 0.0}, {"B", 3.14}, {"C", 3.14}, {"D", 8.8}, {"E", 2.1}, {"F", 1.01}</code> and the top 3 keys would be <code>{"D", "B", "C"}</code>.</p>
  
  <p>I know the procedural way to do this but is there a smarter/functional way to do it in Java 8?</p>
  
  <p>Edit: note that we can put each element of the map into a priority queue of size N, so the time complexity should be M<em>log(N), faster than sorting all M elements which is M</em>log(M).</p>
  
  <p>Edit 2: As requested, this is what I've got:</p>
  
  <pre><code> public static void main(String args[]) {
      final Map&lt;String, Double&gt; map = new HashMap&lt;String, Double&gt;() {{
        put("A", 0.0);
        put("B", 3.14);
        put("C", 3.14);
        put("D", 8.8);
        put("E", 2.1);
        put("F", 1.01);
      }};
      System.out.println("answer= " + getTopN(map, 3).toString());
    }
  
    static List&lt;String&gt; getTopN(final Map&lt;String, Double&gt; map, int n) {
      // Creating priority queue with limit size n
      PriorityQueue&lt;Entry&lt;String, Double&gt;&gt; pq = new PriorityQueue&lt;&gt;(n, Entry.comparingByValue());
      for (Entry&lt;String, Double&gt; entry : map.entrySet()) {
        pq.add(entry);
        if (pq.size() &gt; n) {
          pq.poll();
        }
      }
      Stack&lt;String&gt; stack = new Stack&lt;&gt;();
      while (!pq.isEmpty()) {
        stack.add(pq.poll().getKey());
      }
      final ArrayList&lt;String&gt; answer = new ArrayList&lt;&gt;();
      while (!stack.isEmpty() &amp;&amp; n-- &gt; 0) {
        answer.add(stack.pop());
      }
      return answer;
    }
  </code></pre>