Given a list that could contain duplicates (like the one below), I need to be able to count Each(keyword) number of unique elements.
List list = new ArrayList();
Set set = new HashSet();
list.add("M1");
list.add("M1");
list.add("M2");
list.add("M3");
set.addAll(list);
System.out.println(set.size());
How do I get the count each unique element from the List?
That means i want to know how many "M1" contains in List(list), how many "M2", etc.
The result should be the following:
2 M1
1 M2
1 M3
解决方案
I think you are looking for something like this (I didn't compile it, but it should get you going in the right direction):
List list = ArrayList<>();
Map counts = new HashMap<>();
// Fill list with values....
for (String item:list) {
Integer count = counts.get(item);
if (count == null) {
// This is the first time we have seen item, so the count should be one.
count = 1;
} else {
// Increment the count by one.
count = count + 1;
}
counts.put(item, count);
}
// Print them all out.
for (Entry entry : counts.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey());
}