Reputation: 1925
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<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
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
Upvotes: 2
Views: 2047
Reputation:
Much easier way: use Collections.frequency()
System.out.println("M2: "+Collections.frequency(list,"M2");
will output
M2: 1
Upvotes: 0
Reputation: 17422
Set
won't help you in this case, you need a Map:
List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
list.add("M1");
list.add("M1");
list.add("M2");
list.add("M3");
// ...
Map<String, Integer> counts = new HashMap<String, Integer>();
for(String element: list) {
int currentCount;
if(counts.contains(element)) {
currentCount = counts.get(element) + 1;
} else {
currentCount = 1;
}
counts.put(element, currentCount);
}
// ...
for(String element: counts.keySet()) {
System.out.println("element: " + element + ", times appeared: " + counts.get(element));
}
Upvotes: 2
Reputation: 240928
You are looking for Map<String, Integer>
data structure, not Set
Something like
for(iterating over something){
Integer count =map.get(value);
if( count == null){
map.put(value, 1);
} else{
count++;
map.put(value, count);
}
}
Map is the data structure that maps unique to value
Upvotes: 5
Reputation: 504
means You want to know how many "M1" contains in List(list), how many "M2", instead of using set interface, you can use the Map interface because Map contain the key, value pair format ,i.e. Map data structure.
Map<key,Value>
Upvotes: 0
Reputation: 6497
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<String> list = ArrayList<>();
Map<String, Integer> 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<String, Integer> entry : counts.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey());
}
Upvotes: 2