Problem statement:
Given an array of integer, you have to sort based on count of occurrences in ascending order?
Given an array of integer, you have to sort based on count of occurrences in ascending order?
- import java.util.*;
- public class SortArrayInDesc {
- public static void main(String[] args) {
- int a[] = {2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 1, 1, 1};
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
- for (int i = 0; i < a.length; i++) {
- if (map.containsKey(a[i])) {
- map.put(a[i], map.get(a[i]) + 1);
- } else {
- map.put(a[i], 1);
- }
- }
- ValueComparator<Integer, Integer> comparator = new ValueComparator<Integer, Integer>(map);
- TreeMap<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(comparator);
- sortedMap.putAll(map);
- ArrayList<Integer> lists = new ArrayList<Integer>();
- for (Integer i : sortedMap.keySet()) {
- for (int c = 0; c < sortedMap.get(i); c++) {
- lists.add(i);
- }
- }
- System.out.println(lists.toString());
- }
- }
- import java.util.Comparator;
- import java.util.Map;
- public class ValueComparator<T1, T2 extends Comparable<T2>> implements Comparator<T1> {
- Map<T1, T2> map;
- public ValueComparator(Map<T1, T2> map) {
- this.map = map;
- }
- @Override
- public int compare(T1 k1, T1 k2) {
- T2 val1 = map.get(k1);
- T2 val2 = map.get(k2);
- return val1.compareTo(val2);
- }
- }
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