Find the most common String in ArrayList()

后端 未结 12 946
无人及你
无人及你 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
    慢半拍i (楼主)
    2020-12-08 17:57

    You can make a HashMap. 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.

提交回复
热议问题