Get the keys with the biggest values from a hashmap?

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

I have a HashMap defined like this...

HashMap uniqueNames = new HashMap();

It stor

8条回答
  •  不知归路
    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 hashMap = new HashMap();
        String[] word = sentence.toLowerCase().split(" ");
    
        for (int i=0; i maxCount = null;
    
        for(Entry 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());
    }
    
    }
    

提交回复
热议问题