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

后端 未结 11 1576
后悔当初
后悔当初 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条回答
  •  孤独总比滥情好
    2021-01-18 03:19

    Use Collections.frequency option:

     List list = Arrays.asList("1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8");
          int max = 0;
          int curr = 0;
          String currKey =  null;
          Set unique = new HashSet(list);
    
              for (String key : unique) {
                    curr = Collections.frequency(list, key);
    
                   if(max < curr){
                     max = curr;
                     currKey = key;
                    }
                }
    
              System.out.println("The number "  + currKey + " happens " + max + " times");
    

    Output:

    The number 12 happens 10 times

提交回复
热议问题