Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static ArrayList<Object> frequency (ArrayList<Object> input) {
- if (input.size() == 0) {
- System.out.println("No input was defined");
- return null;
- }
- HashMap<Object, Integer> map = new HashMap<Object, Integer>();
- for (Object obj : input) {
- if (map.containsKey(obj))
- map.put(obj, map.get(obj) + 1);
- else
- map.put(obj, 1);
- }
- ArrayList<Object> output = sortList(map);
- return output;
- }
- private static ArrayList<Object> sortList(HashMap<Object, Integer> map) {
- ArrayList<Object> output = new ArrayList<Object>();
- for (Entry<Object, Integer> entry : map.entrySet()) {
- if (output.size() == 0) {
- output.add(entry.getKey());
- }
- else
- for (int i = 0; i<output.size(); i++) {
- if (entry.getValue()>map.get(output.get(i))) {
- output.add(i, entry.getKey());
- //Not using break here would cause the list to grow for each iteration
- //which gives an infinite loop. The same goes for line 57.
- break;
- }
- if (i == output.size()-1) {
- output.add(entry.getKey());
- break;
- }
- }
- }
- return output;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement