Find the most common String in ArrayList()

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

    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 occurrences = 
      list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
    

提交回复
热议问题