上一次我們用的是一個公共查詢方法傳入字符截取之后的數組查詢次數,這樣消耗性能,
這一次我們通過定義一個實體類存放值和記錄次數,代碼如下、
// ================================================ 分揀思路 // ========================================================= public static void SortingArray() { StringBuilder str = strBuilder(); String name = str.toString(); System.out.println("隨機出來的字符串是:" + name); Map<String,ArrayMap> map = new HashMap<>(); // 賽選字符容器, 便於后期遍歷 Set<String> set = new HashSet<String>(); for (int i = 0; i < name.length(); i++) { String indexStr = name.substring(i,i+1); // System.err.println(indexStr); if(null!=map.get(indexStr)) { // 插入之前先進行判斷 map.get(indexStr).setValue(indexStr); }else { map.put(indexStr, new ArrayMap(indexStr)); set.add(indexStr);// 加入容器 } } for (String string : set) { // 遍歷 System.err.println(map.get(string).toString()); } } } class ArrayMap { private String key; private Integer count; private String value; public void setValue(String value) { if(this.value.equals(value)) { this.count++; }else { this.value = value; this.key = value; } } public ArrayMap() { } public ArrayMap(String key) { this.key = key; this.value=key; this.count=1; } @Override public String toString() { return this.key+"出現的次數是:"+this.count; } }