Obtain higher value element of a HashMap

1

I have a Hashmap which keeps the brand of the car and the times it repeats in a chain,

Map<String,Integer> sh = new HashMap<String, Integer>();

If I make a route to Hashmap I get the following result:

code:

for (Entry<String, Integer> o : sh.entrySet()) {
            System.err.println(o.getKey() + " - " + o.getValue());
        }

Result:

toyota - 1
nissan - 5
mazda - 3

I need to get the mark that has the highest value this case "nissan"

nissan - 5

It's just an example because actually the hashmap I have contains for more than 1500 elements.

    
asked by Eddie Gomez Ochante 22.06.2017 в 10:56
source

2 answers

4

Since the basic question is how to order a Map here I leave you a function to order Maps extracted from the following comment by the author Carter Page

import java.util.*;

public class MapUtil
{
    public static <K, V extends Comparable<? super V>> Map<K, V> 
        sortByValue( Map<K, V> map )
    {
        List<Map.Entry<K, V>> list =
            new LinkedList<Map.Entry<K, V>>( map.entrySet() );
        Collections.sort( list, new Comparator<Map.Entry<K, V>>()
        {
            public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
            {
                return (o1.getValue()).compareTo( o2.getValue() );
            }
        } );

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list)
        {
            result.put( entry.getKey(), entry.getValue() );
        }
        return result;
    }
}

And this is the version for Java 8 that orders in ascending order, for the descending order you just have to uncomment line Collections.reverseOrder() .

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
              .stream()
           .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
              .collect(Collectors.toMap(
                Map.Entry::getKey, 
                Map.Entry::getValue, 
                (e1, e2) -> e1, 
                LinkedHashMap::new
              ));
}

Once you have ordered the map from largest to smallest, you can obtain the highest values with a simple for that it traverses and stores in another map, the elements equal to the highest value until the first element with the lowest value appears.

Map<String, Integer> finalResult = new HashMap<>();
int maxValue = -1;
for(Entry<String,Integer> entry: result.entrySet()){
    if(maxValue<0){
        maxValue = entry.getValue();
    }
    if(entry.getValue()>=maxValue){
        finalResult.put(entry.getKey(),entry.getValue());
    }else{
        break;
    }
}
    
answered by 22.06.2017 / 11:22
source
-2

HashMap: How to obtain the element with the highest value?.

You can use this method, which compares the value of each entry to obtain the maximum value:

 public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){        
    Entry<String, Integer> maxEntry = null;
    Integer max = Collections.max(map.values());

    for(Entry<String, Integer> entry : map.entrySet()) {
        Integer value = entry.getValue();
        if(null != value && max == value) {
            maxEntry = entry;
        }
    }
    return maxEntry;
}

as an example assuming this HashMap :

HashMap map =  new HashMap<String, Integer>() {
{
        put("toyota", 1);
        put("nissan", 5);
        put("mazda", 3);
        put("bmw", 4);
        put("kia", 2);
        put("dacia", 0);
    }
};

The Entry with maximum value would be

   ("nissan", 5)

which can be obtained by calling the method in this way:

  Map.Entry<String, Integer> maxEntry =  getMaxEntry(map);

With Java 8 you can get it this way:

Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();      

System.out.println("maxEntry = " + maxEntry);

you will have the result:

nissan

How to order values in a HashMap?

It can be done using this method:

public static <K, V extends Comparable<? super V>> Map<K, V> 
    sortByValue( Map<K, V> map ){
    List<Map.Entry<K, V>> list =
        new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort( list, new Comparator<Map.Entry<K, V>>(){
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2){
            return (o1.getValue()).compareTo( o2.getValue() );
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list){
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}

The previous method can be called in this way, obtaining the ordered values, as an example the following HashMap :

HashMap map =  new HashMap<String, Integer>() {
{
            put("toyota", 1);
            put("nissan", 5);            
            put("mazda", 3);             
            put("bmw", 4);
            put("kia", 2);
            put("dacia", 0);            
    }
};

We call the method to obtain a Map with the ordered values:

 Map valoreOrdenados =  sortByValue(map);

You can iterate to see the result:

Iterator it = valoreOrdenados.entrySet().iterator();
   while (it.hasNext()) {
    Map.Entry entry = (Map.Entry)it.next();
    System.out.println(entry.getKey() + " => " + entry.getValue());
    it.remove(); // evita ConcurrentModificationException =)
}

resulting in

 dacia => 0
 toyota => 1
 kia => 2
 mazda => 3
 bmw => 4
 nissan => 5
    
answered by 22.06.2017 в 18:15