Sort numbers based on input and occurrence count

Given a array of input, sort it based on the number of occurrence count

Input : [8,0,1,5,5,3,3,3]

Output : [0,1,8,5,5,3,3,3]

Code:

package wordpress;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SortNumbers {
    public static Integer[] sortBasedOnOccurrences(Integer[] input) {
        Map<Integer, Integer> occurrenceCount = new LinkedHashMap<>();
        for (Integer key : input) {
            if (occurrenceCount.containsKey(key)) {
                int count = occurrenceCount.get(key);
                occurrenceCount.put(key, ++count);
            } else {
                occurrenceCount.put(key, 1);
            }
        }

        Map<Integer, Integer> sorted = occurrenceCount
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

        Integer[] result = new Integer[input.length];
        int i = 0;
        for (Map.Entry<Integer, Integer> entry : sorted.entrySet()) {
            int counter = entry.getValue();
            while (counter != 0) {
                result[i++] = entry.getKey();
                counter--;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(sortBasedOnOccurrences(new Integer[]{8, 0, 1, 5, 5, 3, 3, 3}))); // 0 1 8 5 5 3 3 3
        System.out.println(Arrays.toString(sortBasedOnOccurrences(new Integer[]{3, 3, 1, 2, 4}))); // 1 2 4 3 3
        System.out.println(Arrays.toString(sortBasedOnOccurrences(new Integer[]{0,0,1,1,2,2}))); // 0 0 1 1 2 2
        System.out.println(Arrays.toString(sortBasedOnOccurrences(new Integer[]{0}))); // 0
    }
}

Scroll to Top