简体   繁体   中英

count number of loop iteration in Java

Here I have a simple method that finds all duplicate numbers using hashmaps. This only shows the numbers which are duplicated, I need to count the occurrence of each number as well. How can I implement my for loop to fount the frequency of each number?

//driver

public class findDuplicates{

public static void main(String[] args){

int [] input = {2,3,6,5,5,6,9,8,7,7,7,4,1,2,5,5,2};
    dulicates(input);

}
public static void dulicates(int[] MyArray){
        Map<Integer,Integer> HashMap = new HashMap<Integer, Integer>();
        for (int i : MyArray){
            if(!HashMap.containsKey(i)){
                HashMap.put(i, 1);
            }else{
                HashMap.put(i, HashMap.get(i)+1);
            }
        }
        for (Integer i : HashMap.keySet()){
            
                System.out.println("This has a duplicate: " + i );
            }
        }
}

}

You already solved it, you just missed the iteration and check for values > 0.

for(Map.Entry<Integer,Integer> kv : map.entrySet())
{
    if (kv.getValue()>0)
        System.out.println(kv.getKey()+" has "+ kv.getValue() +" duplicate(s)");
}

Based on this logic, consider to implement a getter method for your zipped string.

An example here, using a map that just contains duplicates( just for fun ) and a single set that could help you identifying duplicates and storing uniques. Thanks to that, you could return an int[] without duplicates from the base array.

static int[] showDuplicatesAndGetCleanArray(int[] myArray) //pls change my name
{
    //myArray = {2,3,6,5,5,6,9,8,7,7,7,4,1,2,5,5,2};
    Set<Integer> uniques = new HashSet<>(myArray.length);
    Map<Integer,Integer> dupMap = new HashMap<>(myArray.length);
    for (int i : myArray) 
    {
       if(uniques.contains(i))
          dupMap.put(i, dupMap.get(i)==null ? 1 : dupMap.get(i)+1);
       else
          uniques.add(i);   //else not required, I love useless micro-optimizations   
     }                                

    System.out.println("Total duplicates : [" + (myArray.length-uniques.size())+"]");
    for(Map.Entry<Integer,Integer> kv : dupMap.entrySet())
         System.out.println("- {" + kv.getKey() + "} has " + kv.getValue() +
                            " duplicate" + (kv.getValue()>1 ? "s" : "") ); 

    return uniques.stream().mapToInt(Integer::intValue).toArray();
}

Result:

Total duplicates : [8]
- {2} has 2 duplicates
- {5} has 3 duplicates
- {6} has 1 duplicate
- {7} has 2 duplicates

/* returned  int[] => {1,2,3,4,5,6,7,8,9}  */

There are some methods of the Map interface that make this easy. One is compute() .

  • if the value is null, initialize it to some value, otherwise process the existing value
  • An example of the above is compute(i, (k,v)-> v == null? 1: v + 1 which says if the value for the key is null , initialize to 1 , otherwise, add 1 to existing value .
public static void main(String[] args) {
    int [] input = {2,3,6,5,5,6,9,8,7,7,7,4,1,2,5,5,2};
    duplicates(input);
}
    
public static void duplicates(int[] myArray){
    Map<Integer,Integer> freq = new HashMap<>();
    // perform a frequency count of the array
    for (int i : myArray) {
        freq.compute(i, (k,v)-> v == null ? 1 : v + 1);
    }
    
    // now just print the duplicates and their count.
    System.out.println("Duplicates");
    freq.forEach((k,v) -> {
        if (v > 1) {
            System.out.printf("%s occurs %s times.%n", k,v);
        }
    });
}

Prints

Duplicates
2 occurs 3 times.
5 occurs 4 times.
6 occurs 2 times.
7 occurs 3 times.

As I feel this might be a homework, you should do some of the figuring our for yourself, so I will give to the basic idea but not the code. That is for you to figure out.

A hashmap allows you to use a key to access a value. So for each unique value found in the input.

Check if there is a element in the hashmap with that key, If not place a new element in the hashmap withe the value found as its key, and a 1 as its value.

Else if the there is an item in the hashmap with that key, pull the value out, increment it and put it back under that key.

Have your function end by returning the hashmap.

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