计算循环迭代次数

sin*_*ayo 0 java

这里我有一个简单的方法,使用 s 查找所有重复的数字HashMap。这仅显示重复的数字。我还需要计算每个数字的出现次数。如何实现for循环来计算每个数字的频率?

//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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ara*_*ran 5

你已经解决了它,你只是错过了迭代并检查值 > 0。

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

基于此逻辑,考虑为压缩字符串实现getter方法。

这里的一个例子,使用一个只map包含重复项(只是为了好玩)和一个set可以帮助您识别重复项和存储唯一项的单个项。因此,您可以int[]从基本数组中返回没有重复项的值。

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();
}
Run Code Online (Sandbox Code Playgroud)

结果:

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}  */
Run Code Online (Sandbox Code Playgroud)