find the frequency of elements in a java array

后端 未结 9 1550
灰色年华
灰色年华 2020-12-03 16:40

I have an int array:

{1,2,4,2,3,5,6,4,3}

How can I find frequencies of array elements like 1=1,2=2,3=2,4=4... I need a class w

9条回答
  •  青春惊慌失措
    2020-12-03 17:10

    You can also try below code,

        Map map = new HashMap<>();
        int arr[] = new int[]{2, 2, 3, 3, 4, 5, 6, 7, 9, 9, 0, 4, 2};
    
        for (int i = 0; i < arr.length; i++) {
            Integer count = map.getOrDefault(arr[i], 0);
            map.put(arr[i], count + 1);
        }
    
        //Print the map to see the occurrence
        map.forEach((key, value) -> {
            System.out.println(key + " -> " + value);
        });
    

提交回复
热议问题