Arraylist查找连续重复元素的数量

时间:2019-05-13 05:26:03

标签: java arraylist

我正在尝试在数组列表中找到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}的输出。

5 个答案:

答案 0 :(得分:1)

这里一种简单的方法是只迭代一次arraylist,然后继续进行计数:

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)}

答案 1 :(得分:0)

因为映射是键-值。

在您的代码中:

  

hm.put(a,(j == null)?1:j + 1);

a变量是键。因此,无论何时“ a”等于“ 20”,都将映射相同的值。

更多此处:https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

答案 2 :(得分:0)

  Set<Integer> distinctSet = new HashSet<>(answerSheerPacketList);
    HashSet<Integer,Integer> elementCountSet=new HashSet<>();
    for (Integer element: distinctSet) {
    elementCountSet.put(element,Collections.frequency(answerSheerPacketList, element));

    }

答案 3 :(得分:0)

这是计算数组中连续元素的行程的经典问题。为了简洁起见,我在代码中将数组重命名为arr

    int run = 1;
    for (int i = 0; i < n; ++i) {   // n is the size of array
        if (i + 1 < n && arr[i] == arr[i + 1]) {
            run++;        // increment run if consecutive elements are equal
        } else {
            System.out.println(arr[i] + "=" + run + ", ");
            run = 1;      // reset run if they are not equal
        }
    }

在性能方面,这种方法不是理想的,并且在 O n )中运行,其中 n 是元素中的元素数量数组。

答案 4 :(得分:0)

基本上,您需要的是频率计数。以下代码将通过您的answerSheerPacketList数组进行一次操作:

int[] answerSheerPacketList = // initialization

Map<Integer, Integer> frequencyCount = new LinkedHashMap<>();
for (int i : answerSheerPacketList) {
    Integer key = Integer.valueOf(i);
    if (frequencyCount.containsKey(key)) {
        frequencyCount.put(key, Integer.valueOf(frequencyCount.get(key) + 1));
    } else {
        frequencyCount.put(key, Integer.valueOf(1));
    }
}

for (Integer key : frequencyCount.keySet()) {
    System.out.println("Element " + key + " occurs: " + frequencyCount.get(key)
                       + " times");
}