Advertisement
karlstrigen

Untitled

Feb 17th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1.     public static ArrayList<Object> frequency (ArrayList<Object> input) {
  2.         if (input.size() == 0) {
  3.             System.out.println("No input was defined");
  4.             return null;
  5.         }
  6.         HashMap<Object, Integer> map = new HashMap<Object, Integer>();
  7.         for (Object obj : input) {
  8.             if (map.containsKey(obj))
  9.                 map.put(obj, map.get(obj) + 1);
  10.             else
  11.                 map.put(obj, 1);
  12.         }
  13.         ArrayList<Object> output = sortList(map);
  14.         return output;
  15.     }
  16.  
  17.     private static ArrayList<Object> sortList(HashMap<Object, Integer> map) {
  18.         ArrayList<Object> output = new ArrayList<Object>();
  19.         for (Entry<Object, Integer> entry : map.entrySet()) {
  20.             if (output.size() == 0) {
  21.                 output.add(entry.getKey());
  22.             }
  23.             else
  24.                 for (int i = 0; i<output.size(); i++) {
  25.                     if (entry.getValue()>map.get(output.get(i))) {
  26.                         output.add(i, entry.getKey());
  27.                         //Not using break here would cause the list to grow for each iteration
  28.                         //which gives an infinite loop. The same goes for line 57.
  29.                         break;
  30.                     }
  31.                     if (i == output.size()-1) {
  32.                         output.add(entry.getKey());
  33.                         break;
  34.                     }
  35.                 }
  36.            
  37.         }
  38.         return output;
  39.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement