Looking to get the frequency of an int array through a hashmap

829 Views Asked by At
public int[] topKFrequent(int[] nums, int k) {
    if (nums == null || nums.length == 0 || k <= 0) return new int[0];
    Map<Integer, Integer> freqMap = new HashMap<>();
    for (int currNum : nums) freqMap.put(currNum, freqMap.getOrDefault(currNum, 0)+1);

I don't understand what the .getOrDefault(currNum, 0)+1); is doing, but it seems to calculate the frequency properly. I'd like some clearance on this method please and how exactly it's working.

2

There are 2 best solutions below

2
patrinox On BEST ANSWER

The getOrDefault(Object key, V defaultValue) method of Map interface, implemented by HashMap class is used to get the value mapped with specified key. If no value is mapped with the provided key then the default value is returned.

Syntax: default V getOrDefault(Object key, V defaultValue)

Parameters: This method accepts two parameters:

  • key: which is the key of the element whose value has to be obtained.

  • defaultValue: which is the default value that has to be returned, if no value is mapped with the specified key.

Return Value: This method returns value mapped with the specified key, otherwise default value is returned.

Reference: https://www.geeksforgeeks.org/hashmap-getordefaultkey-defaultvalue-method-in-java-with-examples/

So, by using that method, first, you're trying to get key's value from the freqMap. If you can find it in map, then you're adding 1 to it and putting it back to freqMap. So, that means that you encountered this key before. Otherwise, that method , .getOrDefault(), returns you default value, which is 0, then you're adding 1 to it since you encountered it recently. And putting that value 1 to back to map. So, in the future, when you see that key again, you'll get it's value 1 that you added to the map before, will increase it to 2, and will put it back into the map.

0
Oleg Cherednik On
public static int[] getTopFrequent(int[] nums, int k) {
    // build a map: key - number, value - total amount
    Map<Integer, Long> map = Arrays.stream(nums)
                                   .boxed()
                                   .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    // create a PriorityQueue based on Map.Entry. Elements are sorted according to comparator: the
    // most frequent numbers first
    Queue<Map.Entry<Integer, Long>> queue =
            new PriorityQueue<>(comparingLong((Map.Entry<Integer, Long> one) -> one.getValue()).reversed());

    queue.addAll(map.entrySet());

    // build final resul
    int[] res = new int[Math.max(queue.size(), k)];

    for (int i = 0; i < res.length; i++)
        res[i] = queue.remove().getKey();

    return res;
}