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. // Add item to map
  27. Integer numOfOccur = 1;
  28. Integer prevNumOfOccur = map.put(item, numOfOccur);
  29. // Correct number of occurence if it's not first time it's added
  30. if (prevNumOfOccur != null) {
  31. numOfOccur = map.put(item, prevNumOfOccur + numOfOccur);
  32. }
  33. // Correct mostPopularItem
  34. if (numOfOccur > maxNumOfOccurence) {
  35. mostPopularItem = item;
  36. }
  37. }
  38.  
  39. return mostPopularItem;
  40. }
  41. }
Success #stdin #stdout 0.04s 2184192KB
stdin
Standard input is empty
stdout
Most popular item: 1