Remove top or bottom n map elements
I have a HashMap as shown below:
map.put("1","One"); \\KV1
map.put("3","Three"); \\KV2
map.put("2","Two"); \\KV3
map.put("5","Five"); \\KV4
map.put("4","Four"); \\KV5
Is there any function where I can get 3 key pairs (KV1, KV2, KV3) or bottom 3 (KV3, KV4, KV5)? or could it be any function with which I can remove the top n or bottom n elements?
Thanks in advance.
source to share
There are some terrible answers to this question.
First, it depends on what you mean by top. Insert order or ordered sort order?
A LinkedHashMap preserves the insertion order. A TreeMap maintains its keys in a natural sort order.
If it is a sorted map, you can query the view of the keys using Treemap.headMap (key K) , tailMap () and subMap () ;
If this is the order of insertion, you will need to extract the submap yourself. Guava provides a Maps helper called Maps.filterKeys that will allow you to view the basemap moved by the predicate you pass. This is useful if you don't want to copy the map, just view it differently. Of course, you can always copy the resulting map if that's what you want, or throw in your own more specialized case.
This question shows how to write a generic submarine method for LinkedHashMaps.
source to share
LinkedHashMap
maintains a linked list of records in map
the order in which they were inserted.
Map<String,String> map = new LinkedHashMap<String, String>();
map.put("1","One"); //KV1
map.put("3","Three"); //KV2
map.put("2","Two"); //KV3
map.put("5","Five"); //KV4
map.put("4","Four"); //KV5
for(Map.Entry<String, String> mapentry : map.entrySet() ){
System.out.println(mapentry.getKey()); // you can get the keys and values
System.out.println(mapentry.getValue());
}
source to share