Find the most common String in ArrayList()

后端 未结 12 948
无人及你
无人及你 2020-12-08 16:59

Is there a way to find the most common String in an ArrayList?

ArrayList list = new ArrayList<>();
list.add(\"t         


        
12条回答
  •  旧时难觅i
    2020-12-08 18:00

    With this method, if there is more than one most common elements in your ArrayList, you get back all of them by adding them to a new ArrayList.

    public static void main(String[] args) {
    
     List  words = new ArrayList<>() ; 
    
    words.add("cat") ; 
    words.add("dog") ; 
    words.add("egg") ; 
    words.add("chair") ; 
    words.add("chair") ; 
    words.add("chair") ; 
    words.add("dog") ; 
    words.add("dog") ;  
    
    Map count = new HashMap<>() ; 
    
        for (String word : words) {  /* Counts the quantity of each 
                                          element */
            if (! count.containsKey(word)) {             
                count.put(word, 1 ) ; 
            }
    
            else {
                int value = count.get(word) ; 
                value++ ; 
    
                count.put(word, value) ;
            }       
        }
    
        List  mostCommons = new ArrayList<>() ; /* Max elements  */
    
        for ( Map.Entry e : count.entrySet() ) {
    
            if (e.getValue() == Collections.max(count.values() )){
                                /* The max value of count  */
    
                mostCommons.add(e.getKey()) ;
            }   
        }
    
        System.out.println(mostCommons);
    
     }
    
    }
    

提交回复
热议问题