×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Gerrit Viljoen
Added: Apr 30, 2014 12:50 PM
Views: 24
Gets the most occurring element in the collection.

For Apache Commons Collections 4 Bag.
import org.apache.commons.collections4.Bag;
  1.     public static <T> T getMax(Bag<T> collection) {
  2.         if (collection == null) {
  3.             return null;
  4.         } else if (collection.isEmpty()) {
  5.             return null;
  6.         } else {
  7.             int count = Integer.MIN_VALUE;
  8.             T object = null;
  9.             for (T item : collection) {
  10.                 final int hz = collection.getCount(item);
  11.                 if (hz > count) {
  12.                     count = hz;
  13.                     object = item;
  14.                 }
  15.             }
  16.             return object;
  17.         }
  18.     }