1. 程式人生 > >記錄陣列中出現的數字並統計個數

記錄陣列中出現的數字並統計個數

public class t02 {
public static void main(String args[]){
int [] arr = {1,2,2,2,3,3,4,4,4,4};
testaaa(arr);
}


public static void testaaa(int [] str) {
   Map<Integer, Integer> map=new HashMap<>();
   for (int i = 0; i < str.length; i++) {
       if(map.containsKey(str[i])) {
           map.put(str[i], map.get(str[i])+1);//原來有則+1
       }else {
           map.put(str[i], 1); //原來沒有則放一個
       }
   }

   for (Entry<Integer, Integer> entry : map.entrySet()) {
       System.out.println("數字"+entry.getKey()+"出現了"+entry.getValue()+"次");
   }
}

}