EspenG EspenG - 4 years ago 158
Java Question

Find the most common String in ArrayList()

Wonder if there is an way to find the most common

String
in a
ArrayList
.

ArrayList<String> list = new ArrayList<>();
list.add("test");
list.add("test");
list.add("hello");
list.add("test");


So is there an way to find the word "test" from this list
["test","test","hello","test"]
?

Answer Source

Don't reinvent the wheel and use the frequency method of the Collections class:

public static int frequency(Collection<?> c, Object o)

Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).

If you need to count the occurrences for all elements, use a Map and loop cleverly :) Or put your list in a Set and loop on each element of the set with the frequency method above. HTH

EDIT / Java 8: If you fancy a more functional, Java 8 one-liner solution with lambdas, try:

Map<String, Long> occurrences = 
  list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download