find the frequency of elements in a java array

后端 未结 9 1520
灰色年华
灰色年华 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:13

    Using Java-8 we can find the frequency of an array in a single line.

    Map freq = Arrays.stream(a).boxed().
                              collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    

    Also, since the question demands we need to return an array

    public Object[] getFrequencies(int[] a) {
        Map freq = Arrays.stream(a).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        return freq.entrySet().toArray();
    }
    

提交回复
热议问题