hashmap - How to Get All the Min Values from a Hash Map in Java -
i have hash map keys objects of type request , values of type integer. use following code iterate through map , minimum values , add keys list. emphasize because keys unique values can duplicate, therefore there may more 1 map elements minimum value.
however, code gives me single such element, is, first finds through iteration, though know there more. example, let map has following requests - i.e. keys (i give request ids): 3 | 5 | 2 , respective values are: 8 | 4 | 4. thus, @ example have 2 minimum elements, is, 2 elements share minimum value, id 5 , id 2, both value 4. code add list element id 5, is, first 1 of them.
i have note there similar thread (key maximum value in hashtable) provided solution not work in case.
here code:
entry<request, integer> min = null; list<request> minkeylist = new arraylist<request>(); for(entry<request, integer> entry : this.map.entryset()) { if (min == null || min.getvalue() > map.getvalue()) { min = entry; minkeylist.add(entry.getkey()); }
any suggestion or explanation why happenning appreciated.
edit: new approach
well, found solution. not elegant, works. here code.
// list finding min value list<integer> minvallist = new arraylist<integer>(); // list keeping keys of elements min value list<request> minkeylist = new arraylist<request>(); // scan map , put values value list for(entry<request, integer> entry : this.map.entryset()) { minvallist.add(entry.getvalue()); } // scan map for(entry<request, integer> entry: this.map.entryset()) { // find min value if(entry.getvalue() == collections.min(minvallist)) { // add keys of elements min value @ keylist minkeylist.add(entry.getkey()); } }
i suggest two-step process:
- find minimum, store in
min
- find elements value equal
min
here code sample:
// find minimum first int min = integer.min_value; for(entry<request, integer> entry : this.map.entryset()) { min = math.min(min, map.getvalue()) } // add elements have value equal min list<request> minkeylist = new arraylist<request>(); for(entry<request, integer> entry : this.map.entryset()) { if(min.getvalue() == min) { minkeylist.add(entry.getkey()); } }
Comments
Post a Comment