Find the most common String in ArrayList()

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

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

    Map 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 mostRepeated = null;
    for(Map.Entry e: stringsCount.entrySet())
    {
        if(mostRepeated == null || mostRepeated.getValue()

    And show the most common string:

    if(mostRepeated != null)
            System.out.println("Most common string: " + mostRepeated.getKey());
    

提交回复
热议问题