Get the minimum value key in a hashtable

I have a hashtable in java, as shown below, and I'm trying to get a key that has a minimum value. Obviously, I can iterate over all the elements to find it, but is there an easier way to do this?

Hashtable<Object, Integer> hash= new Hashtable<Object, Integer>(); 
+6
source share
4 answers

Using Hashtable, no. But instead, you can use TreeMap .

Red-Ebony NavigableMap . The card is sorted in accordance with the natural order of its keys or the comparator, provided the card is created, depending on which constructor is used.

It has a firstKey() method that provides the exact functionality you want. C>


Grr, values, not keys. No, then you will need to iterate.

I would say that in this case you should use a separate card (Multimap?) To store feedback.

 Map<Object, Integer> hash= new Hashtable<Object, Integer>(); SortedSetMultimap<Integer, Object> reverse = TreeMultimap.create(); 

whenever you put key , value something in hash , also put value , key in reverse . then get the lowest value using reverse.keySet().first()

( Guava is required for this solution)

+10
source

Instead of reusing it, you can use the library function Collections.min (Collection, Comparator) over entrySet() .

SAMPLE

 public static void main(String[] args) { HashMap<String,Integer> map = new HashMap<String,Integer>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); System.out.println( Collections.min(map.entrySet(), new Comparator<Map.Entry<String,Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { return o1.getValue().intValue() - o2.getValue().intValue(); }}) .getKey() ); } 
+3
source

It seems like the easiest way to do this is to iterate over the elements. If the name hashtable hash:

 Object minObj= null; int min= Integer.MAX_VALUE; for(Map.Entry<Object, Integer> x: hash.entrySet()){ if(x.getValue() < min){ min= x.getValue(); minObj= x.getKey(); } } 
0
source

The minimum value can also be found,

  Hashtable h = new Hashtable(); h.put(10, "aaa"); h.put(1, "aab"); h.put(12, "aabwqkjdg"); Set set = h.keySet(); TreeSet treeSet= new TreeSet(); treeSet.addAll(set); System.out.println("Last :"+treeSet.first()); 

I just took the example keys as a whole.

0
source

Source: https://habr.com/ru/post/926766/


All Articles