Sunday, May 19, 2019

How do you sort an array based on count of occurrences in ascending order

Problem statement:
Given an array of integer, you have to sort based on count of occurrences in ascending order?
  1. import java.util.*;
  2. public class SortArrayInDesc {
  3.     public static void main(String[] args) {
  4.         int a[] = {2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 1, 1, 1};
  5.         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  6.         for (int i = 0; i < a.length; i++) {
  7.             if (map.containsKey(a[i])) {
  8.               map.put(a[i], map.get(a[i]) + 1);
  9.             } else {
  10.                 map.put(a[i], 1);
  11.             }
  12.         }
  13.         ValueComparator<Integer, Integer> comparator = new ValueComparator<Integer, Integer>(map);
  14.         TreeMap<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(comparator);
  15.         sortedMap.putAll(map);
  16.         ArrayList<Integer> lists = new ArrayList<Integer>();
  17.         for (Integer i : sortedMap.keySet()) {
  18.             for (int c = 0; c < sortedMap.get(i); c++) {
  19.                 lists.add(i);
  20.             }
  21.         }
  22.         System.out.println(lists.toString());
  23.     }
  24. }
  1. import java.util.Comparator;
  2. import java.util.Map;
  3. public class ValueComparator<T1, T2 extends Comparable<T2>> implements Comparator<T1> {
  4.     Map<T1, T2> map;
  5.     public ValueComparator(Map<T1, T2> map) {
  6.         this.map = map;
  7.     }
  8.     @Override
  9.     public int compare(T1 k1, T1 k2) {
  10.         T2 val1 = map.get(k1);
  11.         T2 val2 = map.get(k2);

  12.         return val1.compareTo(val2);
  13.     }
  14. }
Output:
[5, 1, 1, 1, 2, 2, 2, 2, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4, 4]

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...