gpt4 book ai didi

java - Arraylist求连续重复元素的个数

转载 作者:行者123 更新时间:2023-12-02 09:54:25 24 4
gpt4 key购买 nike

我正在尝试查找数组列表中重复元素的计数。例如,如果名为“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}

最佳答案

这里的一个简单方法是只迭代数组列表一次,然后在进行过程中保持计数:

List<Integer> list = new ArrayList<>();
list.add(20);
list.add(20);
list.add(30);
list.add(40);
list.add(40);
list.add(20);
list.add(20);
list.add(20);

Integer curr = null;
int count = 0;
System.out.print("{");
for (int val : list) {
if (curr == null) {
curr = val;
count = 1;
}
else if (curr != val) {
System.out.print("(" + curr + ", " + count + ")");
curr = val;
count = 1;
}
else {
++count;
}
}
System.out.print("(" + curr + ", " + count + ")");
System.out.print("}");

{(20, 2)(30, 1)(40, 2)(20, 3)}

关于java - Arraylist求连续重复元素的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56106181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com