📌  相关文章
📜  按频率对元素进行排序|设置5(使用Java Map)

📅  最后修改于: 2021-04-17 09:26:08             🧑  作者: Mango

给定一个整数数组,请按元素的降序对数组进行排序,如果两个元素的频率相同,则按升序进行排序

例子:

Input: arr[] = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}
Output: 3 3 3 3 2 2 2 12 12 4 5
Explanation :
No. Freq
2  : 3
3  : 4
4  : 1
5  : 1
12 : 2

Input: arr[] = {4, 4, 2, 2, 2, 2, 3, 3, 1, 1, 6, 7, 5}
Output: 2 2 2 2 1 1 3 3 4 4 5 6 7

以下帖子中讨论了不同的方法:
按频率对元素进行排序|套装1
按频率对元素进行排序|套装2
按频率对数组元素进行排序|设置3(使用STL)
按频率对元素进行排序|第4组(使用哈希的有效方法)

方法:

此集合中已使用Java Map来解决此问题。 Java.util.Map接口表示键和值之间的映射。 Map接口不是Collection接口的子类型。因此,它的行为与其余集合类型略有不同。

地图接口

在下面的程序中:

  • 在地图中获取元素及其计数
  • 通过使用比较器接口,比较给定列表中元素的频率。
  • 使用此比较器可以通过实现Collections.sort()方法对列表进行排序。
  • 打印排序列表。

程序:

import java.util.*;
  
public class GFG {
  
    // Driver Code
    public static void main(String[] args)
    {
  
        // Declare and Initialize an array
        int[] array = { 4, 4, 2, 2, 2, 2, 3, 3, 1, 1, 6, 7, 5 };
  
        Map map = new HashMap<>();
        List outputArray = new ArrayList<>();
  
        // Assign elements and their count in the list and map
        for (int current : array) {
            int count = map.getOrDefault(current, 0);
            map.put(current, count + 1);
            outputArray.add(current);
        }
  
        // Compare the map by value
        SortComparator comp = new SortComparator(map);
  
        // Sort the map using Collections CLass
        Collections.sort(outputArray, comp);
  
        // Final Output
        for (Integer i : outputArray) {
            System.out.print(i + " ");
        }
    }
}
  
// Implement Comparator Interface to sort the values
class SortComparator implements Comparator {
    private final Map freqMap;
  
    // Assign the specified map
    SortComparator(Map tFreqMap)
    {
        this.freqMap = tFreqMap;
    }
  
    // Compare the values
    @Override
    public int compare(Integer k1, Integer k2)
    {
  
        // Compare value by frequency
        int freqCompare = freqMap.get(k2).compareTo(freqMap.get(k1));
  
        // Compare value if frequency is equal
        int valueCompare = k1.compareTo(k2);
  
        // If frequency is equal, then just compare by value, otherwise -
        // compare by the frequency.
        if (freqCompare == 0)
            return valueCompare;
        else
            return freqCompare;
    }
}
输出:
2 2 2 2 1 1 3 3 4 4 5 6 7