Sorting ArrayList based on number of duplicates? [closed]

You can use Collections#frequency to get the occurrences, and map the the object accordingly. This way if the same object is encountered multiple times, it wont be stored more than once:

    // Map to store in
    HashMap<Integer, Object> map = new HashMap<Integer, Object>();
    // Iterate
    for (Object obj : list) {
        // Map according to occurrences
        map.put(Collections.frequency(list, obj), obj);
    }

If you want to access the contents in ascending order, you can stream the key set and sort it:

map.keySet().stream().sorted().forEach(k -> System.out.println(map.get(k) + ":" + k));

If you want to access the contends in descending order, you can use make a comparator that is opposite of Integer#compare:

map.keySet().stream().sorted((k1, k2) ->  (k1 < k2) ? 1 : ((k1 == k2) ? 0 : -1)).forEach(k -> System.out.println(map.get(k) + ":" + k));

If you do not wish to stream your key set (say you are accessing at different lines), you can use an Iterator instead:

Iterator<Integer> descending = map.keySet().stream().sorted((k1, k2) ->  (k1 < k2) ? 1 : ((k1 == k2) ? 0 : -1)).iterator();
Iterator<Integer> ascending = map.keySet().stream().sorted().iterator();

while(descending.hasNext()) {
    int i = descending.next();
    System.out.println(map.get(i) + ":" + i);
}
while(ascending.hasNext()) {
    int i = ascending.next();
    System.out.println(map.get(i) + ":" + i);
}

Leave a Comment