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