Get the keys with the biggest values from a hashmap?

后端 未结 8 1689
时光取名叫无心
时光取名叫无心 2020-12-06 02:01

I have a HashMap defined like this...

HashMap uniqueNames = new HashMap();

It stor

相关标签:
8条回答
  • 2020-12-06 02:33

    Most obvious, now allowing for multiple with largest occurrence value:

    Integer largestVal = null;
    List<Entry<String, Integer>> largestList = new ArrayList<Entry<String, Integer>>();
    for (Entry<String, Integer> i : uniqueNames.entrySet()){
         if (largestVal == null || largestVal  < i.getValue()){
             largestVal = i.getValue();
             largestList .clear();
             largestList .add(i);
         }else if (largestVal == i.getValue()){
             largestList .add(i);
         }
    }
    

    Another option would be to use Guava's BiMap.

    BiMap<String, Integer> uniqueNames = ...;
    List<Integer> values = Lists.newArrayList(uniqueNames.values());
    Collections.sort(values);
    String name = uniqueNames.inverse().get(values.get(0));
    
    0 讨论(0)
  • 2020-12-06 02:34

    This is my approach.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    
    public class FindWordCounter {
    
    public static void main(String[] args) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    
        try {
    
            System.out.println("Enter the sentence: ");
            String sentence = bufferedReader.readLine();
            FindWordCounter.countWord(sentence);
    
        }   catch (IOException e) {
    
            System.out.println(e);
    
        }
    }
    
    public static void countWord(String sentence) {
    
        Map<String, Integer> hashMap = new HashMap<String, Integer>();
        String[] word = sentence.toLowerCase().split(" ");
    
        for (int i=0; i<word.length; i++) {
    
            if (hashMap.containsKey(word[i])) {
    
                int count = hashMap.get(word[i]);
                hashMap.put(word[i], count + 1);
    
            }
            else {
                hashMap.put(word[i], 1);
            }
        }
    
        Entry<String,Integer> maxCount = null;
    
        for(Entry<String,Integer> entry : hashMap.entrySet()) {
    
            if (maxCount == null || entry.getValue() > maxCount.getValue()) {
                maxCount = entry;
    
            }
        }
    
        System.out.println("The word with maximum occurence is: " + maxCount.getKey() 
                                + " and the number of occurence is: " + maxCount.getValue());
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题