fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // Test getMostPopularItem method
  13. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 6, 1, 1, 1);
  14. int mostPopularItem = getMostPopularItem(list);
  15. System.out.println("Most popular item: " + mostPopularItem);
  16. }
  17.  
  18. public static <T> T getMostPopularItem(Iterable<T> collection) {
  19. // Create new map that will hold pairs:
  20. // (item) -> (number of it's occurence in collection)
  21. Map<T, Integer> map = new HashMap<>();
  22.  
  23. T mostPopularItem = null;
  24. int maxNumOfOccurence = 0;
  25. for (T item : collection) {
  26. Integer numOfOccur = map.compute(item, (k, v) -> {
  27. return v == null ? 1 : v + 1;
  28. });
  29. // Correct mostPopularItem
  30. if (numOfOccur > maxNumOfOccurence) {
  31. mostPopularItem = item;
  32. }
  33. }
  34.  
  35. return mostPopularItem;
  36. }
  37. }
Success #stdin #stdout 0.14s 2184192KB
stdin
Standard input is empty
stdout
Most popular item: 1