Find the element with highest occurrences in an array [java]

后端 未结 11 1595
后悔当初
后悔当初 2021-01-18 02:36

I have to find the element with highest occurrences in a double array. I did it like this:

int max = 0;
for (int i = 0; i < array.length; i++) {
       in         


        
11条回答
  •  萌比男神i
    2021-01-18 03:27

    The solution with Java 8

           int result = Arrays.stream(array)
               .boxed()
               .collect(Collectors.groupingBy(i->i,Collectors.counting()))
               .values()
               .stream()
               .max(Comparator.comparingLong(i->i))
               .orElseThrow(RuntimeException::new));
    

提交回复
热议问题