Find the most common String in ArrayList()

后端 未结 12 930
无人及你
无人及你 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条回答
  • 2020-12-08 17:56

    You could use a HashMap<String,Integer>. Looping through the array, you can check for each String if it is not already a Key of your HashMap, add it and set the value to 1, if it is, increase its value by 1.

    Then you have a HashMap with all unique Strings and an associated number stating their amount in the array.

    0 讨论(0)
  • 2020-12-08 17:57

    You can make a HashMap<String,Integer>. If the String already appears in the map, increment its key by one, otherwise, add it to the map.

    For example:

    put("someValue", 1);
    

    Then, assume it's "someValue" again, you can do:

    put("someValue", get("someValue") + 1);
    

    Since the key of "someValue" is 1, now when you put it, the key will be 2.

    After that you can easily go through the map and extract the key that has the highest value.

    I didn't write a full solution, try to construct one, if you have problems post it in another question. Best practice is to learn by yourself.

    0 讨论(0)
  • 2020-12-08 17:59

    Don't reinvent the wheel and use the frequency method of the Collections class:

    public static int frequency(Collection<?> c, Object o)
    

    Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).

    If you need to count the occurrences for all elements, use a Map and loop cleverly :) Or put your list in a Set and loop on each element of the set with the frequency method above. HTH

    EDIT / Java 8: If you fancy a more functional, Java 8 one-liner solution with lambdas, try:

    Map<String, Long> occurrences = 
      list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
    
    0 讨论(0)
  • 2020-12-08 18:00

    I think the best way to do it is using maps containing counts.

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

    And iterate over your array filling this map:

    for(String s: list)
    {
      Integer c = stringsCount.get(s);
      if(c == null) c = new Integer(0);
      c++;
      stringsCount.put(s,c);
    }
    

    Finally, you can get the most repeated element iterating over the map:

    Map.Entry<String,Integer> mostRepeated = null;
    for(Map.Entry<String, Integer> e: stringsCount.entrySet())
    {
        if(mostRepeated == null || mostRepeated.getValue()<e.getValue())
            mostRepeated = e;
    }
    

    And show the most common string:

    if(mostRepeated != null)
            System.out.println("Most common string: " + mostRepeated.getKey());
    
    0 讨论(0)
  • 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 <String> 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<String,Integer> 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 <String> mostCommons = new ArrayList<>() ; /* Max elements  */
    
        for ( Map.Entry<String,Integer> e : count.entrySet() ) {
    
            if (e.getValue() == Collections.max(count.values() )){
                                /* The max value of count  */
    
                mostCommons.add(e.getKey()) ;
            }   
        }
    
        System.out.println(mostCommons);
    
     }
    
    }
    
    0 讨论(0)
  • 2020-12-08 18:02
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    

    public class StringChecker {

    public static void main(String[] args) {
    ArrayList<String> string;
    string = new ArrayList<>(Arrays.asList("Mah", "Bob", "mah", "bat", "MAh", "BOb"));
    Map<String, Integer> wordMap = new HashMap<String, Integer>();
    
    for (String st : string) {
        String input = st.toUpperCase();
        if (wordMap.get(input) != null) {
            Integer count = wordMap.get(input) + 1;
            wordMap.put(input, count);
        } else {
            wordMap.put(input, 1);
        }
    }
    System.out.println(wordMap);
    Object maxEntry = Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey();
    System.out.println("maxEntry = " + maxEntry);
    

    }

    0 讨论(0)
提交回复
热议问题