Is there a way to find the most common String in an ArrayList?
ArrayList list = new ArrayList<>();
list.add(\"t
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());