Sort Array Input based On Sequence

Given an array of input, print the value based on the sequence of occurrence

Input :   [0,1,2,3,0,0,2,2,3,0]

Output: [0,0,0,0,1,2,2,2,3,3]

Code:
package wordpress;

import java.util.*;
import java.util.stream.Collectors;

public class SequenceOfNumbers {

    private static void sequenceOfCount(Integer[] input) {
        Map<Integer, Integer> countMap = new HashMap<>();
        for (Integer value : input) {
            if (countMap.containsKey(value)) {
                int count = countMap.get(value);
                countMap.put(value, ++count);
            } else {
                countMap.put(value, 1);
            }
        }

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

        List<Integer> result = new LinkedList<>();
        for(Map.Entry<Integer,Integer> value :sortedMap.entrySet()){
            for(int i=0;i<value.getValue();i++){
                result.add(value.getKey());
            }
        }

        System.out.println(result);
    }

    public static void main(String[] args) {
        sequenceOfCount(new Integer[]{0, 1, 2, 3, 0, 0, 2, 2, 3, 0}); //0, 0, 0, 0, 1, 2, 2, 2, 3, 3
        sequenceOfCount(new Integer[]{1,2,3,1,}); // 1 1 2 3
        sequenceOfCount(new Integer[]{-1,1,-1,1}); // -1 -1 1 1
        sequenceOfCount(new Integer[]{4,3,2,1}); // 1 2 3 4
    }
}
Scroll to Top