Find the most common String in ArrayList()

后端 未结 12 938
无人及你
无人及你 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:52

    There are a lot of answers suggesting HashMaps. I really don't like them, because you have to iterate through them once again anyway. Rather, I would sort the List

    Collections.sort(list);
    

    and then loop through it. Something similar to

    String prev = null, mostCommon=null;
    int num = 0, max = 0;
    for (String str:list) {
      if (str.equals(prev)) {
        num++;
      } else {
        if (num>max) {
          max = num;
          mostCommon = str;
        }
        num = 1;
        prev = str;
      }
    }
    

    should do it.

提交回复
热议问题