Find the most common String in ArrayList()

后端 未结 12 931
无人及你
无人及你 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 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 = new ArrayList<>(Arrays.asList("Mah", "Bob", "mah", "bat", "MAh", "BOb"));
    Map wordMap = new HashMap();
    
    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);
    

    }

提交回复
热议问题