【发布时间】:2019-09-30 01:12:11
【问题描述】:
我正在尝试查找数组列表中重复元素的 COUNT。
例如,如果名为“answerSheerPacketList”列表的数组包含像{20,20,30,40,40,20,20,20} 这样的值,我需要显示像{20=2,30=1,40=2,20=3} 这样的输出。
Map<String, Integer> hm = new HashMap<String, Integer>();
for (String a : answerSheerPacketList) {
Integer j = hm.getinsAnswerSheetId(a);
hm.put(a, (j == null) ? 1 : j + 1);
}
// displaying the occurrence of elements in the arraylist
for(Map.Entry<String, Integer> val : hm.entrySet()){
System.out.println("Element " + val.getKey() + " "
"occurs" + ": " + val.getValue()+ " times");
}
当我执行上面的代码时,我得到了像 {20=5,30=1,40=2} 这样的输出,但我试图得到像 {20=2,30=1,40=2,20=3} 这样的输出。
【问题讨论】:
-
问题:您实际想要的最终数据结构是什么?请注意,它不能是普通地图,因为同一个键会出现多次。或者,您只是想要控制台的输出?
-
标题应该是“Arraylist 查找连续重复元素的数量”