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.

+3


source to share


4 answers


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.

+2


source


You can remove n elements from the map without iteration this way



map.keySet().removeAll(Arrays.asList(map.keySet().toArray()).subList(0, 5));

      

+1


source


Use SortedMap like TreeMap instead of HashMap. Then you can iterate over the keys in order. This allows you to find and remove 3 small keys. Remove the three largest keys by searching and then removing the last key three times.

0


source


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());
    }

      

0


source







All Articles