How to maintain a Java TreeMap size to be a constant while adding key-value pairs into the TreeMap?

假如想象 提交于 2019-12-12 03:04:08

问题


CODE IS HERE is a nice and simple example of TreeMap in java to keep track of the key-value pairs added to the map in a sorted order. However, I am unsure on how to ensure that I only keep 10 items in the TreeMap. How to ensure that the size of the TreeMap is always a constant, like 10? So the original problem is: to keep track of the top ten key-value pairs weighted by value in the TreeMap while the stream of key-value keeps coming in.

I want to see how the to write the code in java to constrict the size of the TreeMap. I'm thinking it is something like this: first add the new key-value pair into the TreeMap, then you check the size of the TreeMap, if it is greater than 10, then delete the smallest key-value pair from the TreeMap and the size returns back to 10 and the TreeMap is ready to add a new key-value pair inside of it.

来源:https://stackoverflow.com/questions/37244198/how-to-maintain-a-java-treemap-size-to-be-a-constant-while-adding-key-value-pair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!