Get number of duplicates from ArrayList

社会主义新天地 提交于 2020-01-11 13:59:13

问题


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 of x and x and I want to be able to differentiate what I have, either x or y because in actuality, I could have any object in the ArrayList and I have to be able to tell them apart.

What I was thinking of doing was first converting the ArrayList into a LinkedHashSet, which would keep the ordering and remove the duplicates so I would just have x and y But how would I get the number of each and associate it with the proper element?

Overall what I want to do is to be able to write a toString method that will let me output:

x3y2

But without knowing that x and y are the elements because they could have been something else like z or w.


回答1:


Check out the Multiset in google guava: http://docs.guava-libraries.googlecode.com/git-history/v11.0.2/javadoc/com/google/common/collect/Multiset.html

Example:

Multiset<String> strings = HashMultiset.create(arrayList);
int countX = strings.count("x"); // the count of x

More examples can be found on the Guava wiki.




回答2:


What you want to do is use a HashMap<Object, Long>. 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.




回答3:


Well, for this what you can do is to traverse the list from the end. Keep a counter and keep checking for the change in the object. As soon as you detect a change, replace the number in the counter with the current position + 1. Do this till you reach the first position.



来源:https://stackoverflow.com/questions/9575192/get-number-of-duplicates-from-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!