Get number of duplicates from ArrayList

前端 未结 3 381
自闭症患者
自闭症患者 2021-01-27 20:07

For example, say I have an ArrayList that could contain the following values:

x
x
x
y
y

Now what I want to retrieve is the number

3条回答
  •  甜味超标
    2021-01-27 20:36

    What you want to do is use a HashMap. Store the Object as the key and the Long as the occurrence count.

    Here's some pseudo code which will do what you're trying to do.

    for(x in list) {
     if(x in Map) {
       map.put(x, map.get(x)++);
     } else {
       map.put(x, 1);
     }
    }
    

    You can then iterate through the Map and print the value and occurrence count. I'll let you write that one up. It's easy enough.

提交回复
热议问题