简体   繁体   中英

finding how many times each element is in the array java

So I want to have a base value, lets call it n. If the count of the numbers in an array is equal to n then I want that number to be printed out.

I want this to be done O(n):

Here's what I have, puting the values in a hashmap, how do I then check the count of each key?:

  int[] a = {1, 2, 3, 4, 5, 6, 7, 7, 7, 7};
        int minOfOneNum = a.length/2;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i : a) {
            Integer count = map.get(i);
            map.put(i, count != null ? count + 1 : 0);
        }

EDIT:

Finding the max val

   for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int count = entry.getValue();
            if(count == minOfOneNum){
                System.out.println(entry.getKey() + "Is the max");
            }
            System.out.println(count);
        }

You can iterate over the count values in your map using the keyset:

for(Integer key : map.keySet()) {
  int count = map.get(key);
}

Note that map.put(i, count != null ? count + 1 : 0); is not correct since you have to put 1 into the map if count is null . Otherwise you will not count the first appearance of an element.

Edit: Or as Andy Turner suggested, you can use the entry set:

for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
  int count = entry.getValue();
}

Edit2: If you want to find the maximum you can of course use the same loop:

int max = Integer.MIN_VALUE;
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
  max = Math.max(max, entry.getValue());
}

if(n == max) {
  // do something       
}

Or even nicer using Java 8 streams:

int max = map.values().stream().max(Integer::compare);
if (n == max) {
  // do something
}

Edit3: If you are actually interested in the number that appears most often - and the number of times it appears you can do the following:

int max = Integer.MIN_VALUE;
int maxKey = -1;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    if (max < entry.getValue()) {
        max = entry.getValue();
        maxKey = entry.getKey();
    }
}

System.out.println(maxKey + "appears most often: " + max + " times");

Or again using Java 8 streams:

Map.Entry<Integer, Integer> max;
max = map.entrySet().stream().max((x, y) -> Integer.compare(x.getValue(), y.getValue())).get();

System.out.println(max.getKey() + "appears most often: " + max.getValue() + " times");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM