用map來統計陣列中各個字串的數量
阿新 • • 發佈:2021-08-11
1.背景
想要統計這一個字串陣列中每一個非重複字串的數量,使用map來儲存其key和value。這個需求在實際開發中經常使用到,我以前總是新建一個空陣列來記錄不重複字串,並使用計數器計數,效率低下且麻煩,特此記錄。
2.程式碼實現
public class test { public void makeEqual(String[] words) { Map<String,Integer> maps = new HashMap<>(); for (String str : words) {//遍歷陣列 maps.put(str, maps.getOrDefault(str, 0) + 1);將相同的字串歸類在同一個key中,如果預設為0,自加; } for (Map.Entry<String, Integer> map : maps.entrySet()) {//遍歷map,獲取key,value值 System.out.println(map.getKey()+","+map.getValue()); } } public static void main(String[] args) { test test = new test(); String[] a = {"abcd","aebc","ddho"}; test.makeEqual(a); } }
3.測試結果
aebc,1
ddho,1
abcd,1